Automatic conversion
Java happily puts a smaller type into a bigger box, because nothing can be lost:
public class Main {
public static void main(String[] args) {
int whole = 7;
double decimal = whole;
System.out.println(decimal);
}
}Output
7.0
Think of it like this: Pouring a small cup of water into a big bucket is always safe. Pouring a bucket into a cup might spill.
Casting: forcing a conversion
Going from a bigger type to a smaller one could lose information, so Java makes you say it on purpose. Write the new type in brackets. This is called a cast:
public class Main {
public static void main(String[] args) {
double price = 9.99;
int rupees = (int) price;
System.out.println(rupees);
}
}Output
9
A cast to int simply chops off the decimal part. It does not round: 9.99 becomes 9.
Without the cast, the compiler stops you:
public class Main {
public static void main(String[] args) {
double price = 9.99;
int rupees = price;
}
}Output (the program does not compile)
Main.java:4: error: incompatible types: possible lossy conversion from double to int
int rupees = price;
^Text to numbers
Text like "25" is not a number, even if it looks like one. Convert it like this:
public class Main {
public static void main(String[] args) {
String text = "25";
int number = Integer.parseInt(text);
System.out.println(number + 5);
double d = Double.parseDouble("3.5");
System.out.println(d * 2);
}
}Output
30 7.0
Numbers to text
public class Main {
public static void main(String[] args) {
int age = 30;
String s = String.valueOf(age);
System.out.println(s + "5");
System.out.println("" + age + 1);
}
}Output
305 301
When one side of + is text, Java joins instead of adding. That's why "" + 30 + 1 gives 301, not 31.
Remember:
(int) 9.99chops to9.Integer.parseInt("9")turns text into a number.