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
|x||boolean||x = y||N/A||N/A||N/A||N/A||N/A||N/A||N/A|
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.
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()|
s represents a string such as "45.38", val is a variable or data of the represented type
String s = "37.68"; double price = Double.parseDouble(s);