Java Type Casting
Type casting means changing a value from one data type to another. Java has two kinds: widening (automatic) and narrowing (manual).
Widening casting (automatic)
A smaller type goes into a bigger type without any problem, so Java does it by itself: byte → short → int → long → float → double.
public class Main {
public static void main(String[] args) {
int n = 10;
long l = n; // int to long
double d = n; // int to double
System.out.println(n + " " + l + " " + d);
}
}
10 10 10.0
Narrowing casting (manual)
A bigger type going into a smaller one can lose data, so you must write the cast in brackets. Without it, the code does not compile:
public class Bad {
public static void main(String[] args) {
double d = 9.78;
int n = d;
}
}
Bad.java:4: error: incompatible types: possible lossy conversion from double to int
int n = d;
^
1 error
error: compilation failed
public class Narrow {
public static void main(String[] args) {
double d = 9.78;
int n = (int) d; // the decimal part is cut, not rounded
System.out.println(d + " -> " + n);
long big = 3_000_000_000L;
int small = (int) big; // too big for int, the value is wrong
System.out.println(big + " -> " + small);
int x = 130;
byte b = (byte) x; // byte is only -128 to 127
System.out.println(x + " -> " + b);
}
}
9.78 -> 9
3000000000 -> -1294967296
130 -> -126
The cast of a decimal to an int removes the decimal part (it does not round). Use Math.round() when you want rounding.
Casting in calculations
When you divide two int values, the answer is also an int. Cast one of them to get the decimal:
public class Divide {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println(a / b); // 3
System.out.println((double) a / b); // 3.5
System.out.println(Math.round(7 / 2.0));// 4
}
}
3
3.5
4
Numbers and strings
These are not casts. You use methods to change between a number and a String:
public class Convert {
public static void main(String[] args) {
int age = Integer.parseInt("25");
double price = Double.parseDouble("99.50");
String text = String.valueOf(42);
String text2 = Integer.toString(7);
System.out.println(age + 1);
System.out.println(price + 0.5);
System.out.println(text + text2);
}
}
26
100.0
427
If the text is not a number, parseInt throws a NumberFormatException. We handle it in Java Exceptions.
public class Parse {
public static void main(String[] args) {
int n = Integer.parseInt("abc");
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:565)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Parse.main(Parse.java:3)
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |