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

Basic Type coercion
y
=booleancharbyteshortintlongfloatdouble
xbooleanx = yN/AN/AN/AN/AN/AN/AN/A
charN/Ax=yx=yx=(char)yx=(char)yx=(char)yx=(char)yx=(char)y
byteN/Ax=(byte)yx=yx=(byte)yx=(byte)yx=(byte)yx=(byte)yx=(byte)y
shortN/Ax=yx=yx=yx=(short)yx=(short)yx=(short)yx=(short)y
intN/Ax=yx=yx=yx=yx=(int)yx=(int)yx=(int)y
longN/Ax=yx=yx=yx=yx=yx=(long)yx=(long)y
floatN/Ax=yx=yx=yx=yx=yx=yx=(float)y
doubleN/Ax=yx=yx=yx=yx=yx=yx=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

String Conversions
TypeTo StringFrom String
booleannew Boolean(val).toString()new Boolean(s).booleanValue()
charString.valueOf(val)s.charAt(0)
byteByte.toString(val)Byte.parseByte(s)
shortShort.toString(val)Short.parseShort(s)
intInteger.toString(val)Integer.parseInt(s)
longLong.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);