Managing Variables
Java (and thus JSP) is a typed language. This means that data is stored in different formats during processing.
Normally Java can switch from one type to another as needed but occasionally the compiler is unsure that such a conversion is safe. In those situations a type will need to be coerced by a technique called typecasting.
The general rule of thumb is Java needs typecasting only of data loss is a risk.
Another situation occurs if you wish to print a number, Java will do its best, but it does not know if 0.07 means 7% or $0.07 so we need to be able to format data as well
Primitive Type Conversions
The Primitive types are the 8 builtin types that Java uses. Why Eight? See our article on primitive types
y | |||||||||
---|---|---|---|---|---|---|---|---|---|
= | boolean | char | byte | short | int | long | float | double | |
x | boolean | x = y | N/A | N/A | N/A | N/A | N/A | N/A | N/A |
char | N/A | x=y | x=y | x=(char)y | x=(char)y | x=(char)y | x=(char)y | x=(char)y | |
byte | N/A | x=(byte)y | x=y | x=(byte)y | x=(byte)y | x=(byte)y | x=(byte)y | x=(byte)y | |
short | N/A | x=y | x=y | x=y | x=(short)y | x=(short)y | x=(short)y | x=(short)y | |
int | N/A | x=y | x=y | x=y | x=y | x=(int)y | x=(int)y | x=(int)y | |
long | N/A | x=y | x=y | x=y | x=y | x=y | x=(long)y | x=(long)y | |
float | N/A | x=y | x=y | x=y | x=y | x=y | x=y | x=(float)y | |
double | N/A | x=y | x=y | x=y | x=y | x=y | x=y | x=y |
How to use this chart
Suppose I were to add 2 numbers:
int answer;
answer = (int)( 3.4 + 5.6 ); // equals 9.0
Since the two numbers were decimals (defaulting to type double), the result was also a decimal (double). Since the compiler would think I might need the ".0", I had to use (int) in order to coerce the compiler.
I checked the type of answer, which is int on the "X" row, and the result, which was a double along the "Y" row, so answer = 9.0
becomes x = (int)y
on the chart.
String Conversions
If you need to print out a value, or obtain a value from a string field (eg: request.getparameter() this next chart should be quite helpful
Type | To String | From String |
---|---|---|
boolean | new Boolean(val).toString() | new Boolean(s).booleanValue() |
char | String.valueOf(val) | s.charAt(0) |
byte | Byte.toString(val) | Byte.parseByte(s) |
short | Short.toString(val) | Short.parseShort(s) |
int | Integer.toString(val) | Integer.parseInt(s) |
long | Long.toString(val) | Long.parseLong(s) |
float* | Float.toString(val) | Float.parseFloat(s) |
double* | Double.toString(val) | Double.parseDouble(s) |
s represents a string such as "45.38", val is a variable or data of the represented type
Example
String s = "37.68";
double price = Double.parseDouble(s);