Home › Java Tutorial › Java type casting
Java type casting
Convert between types.
Widening (small to big) is automatic. Narrowing needs a cast in brackets, like (int) 9.78, and drops the decimals. Integer.parseInt turns text into an int and String.valueOf turns a value into text. Dividing two ints gives an int.
Example code
public class Main {
public static void main(String[] args) {
int a = (int) 9.78;
double d = 7;
int n = Integer.parseInt("42");
String s = String.valueOf(3.5);
System.out.println(a);
System.out.println(d);
System.out.println(n + 1);
System.out.println(s + "!");
System.out.println(10 / 4);
System.out.println(10 / 4.0);
}
}