Java Types and Type Conversion (Casting)
In Java, there are primitive types: {short, int, double}. But there are also corresponding number classes, that wraps a class structure around these.
Technically, every variable and expression in Java is of some type.
Java data types are of two kinds: primitive and reference.
- Primitive types: byte, short, int, long, char, float, double.
- Reference types: class, interface, array.
You can convert one data type to another, by a operation
called “casting”. Converting from one type to another is necessary, because sometimes a function f accept type A, and your expression e has type B and you want to do f(e)
. So, you need to convert your e to type A.
The general syntax to do casting is this: (type) myExpression
. For example, if “n” is a “int” and you want to cast it to “double”, do (double) n
.
In the following example, java.lang.Math.pow()
returns a “double”. It can be casted to “int” by including (int)
in front. (if this is removed, the code won't compile.)
import java.lang.Math; class T2 { public int square (int n) { return (int) java.lang.Math.pow(n,2); } } class T1 { public static void main(String[] arg) { T2 x1 = new T2(); double m =x1.square(3); System.out.println(m); } }