3. "Casting" to change variable types
Java is strictly ("strongly") typed
You may have already made an error like this:
public class MyProgram { public static void main(String[] args) { double appleCost = 2.5; double orangeCost = 3.5; //This line is an ERROR: int average = (appleCost + orangeCost)/2; System.out.println("The average cost is:"); System.out.println(average); } }
Java's variables and expressions usually cannot automatically be converted from one type to another. Even a simple line of code line int x = 2.0;
will fail, because 2.0 is a double, and you cannot put a double into an int.
Type Casting
To convert between one type and another, you must perform a "type cast". Sometimes people will just call this a "cast":
public class MyProgram { public static void main(String[] args) { double appleCost = 2.5; double orangeCost = 3.5; double decimalAverage = (appleCost + orangeCost)/2; //(int)decimalAverage converts decimalAverage to an int: int average = (int)decimalAverage; System.out.println("The average cost is:"); System.out.println(average); //prints 3 } }
You can freely convert between any of the eight primitive types. Thus all these lines compile and run:
public class MyProgram { public static void main(String[] args) { int a = (int)2.2; //Becomes 2 int b = (int)2.9; //Also becomes 2 int c = (int)5; //Casts an int to an int, which is not exciting double d = (double)5; //5.0 System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }
You cannot use casting for strings
We will learn the Integer.parseInt, Float.parseFloat, Double.parseDouble, and toString (with radix) functions later. For now, do not try to cast a String or any double quoted text.
Truncation
When you cast from a decimal type (like a double or float) to an integer (byte, short, int, or long), the non-integer portion is removed. Thus, (int)9.99 is the same as 9. (int)-9.99 becomes -9. Notice that this is different from rounding down, since negative numbers get rounded up.
Go ahead and try casting between different variable types:
Warning for advanced programmers: the operator precedence of casting is very high. (int)3.5+2.5 is the same as ((int)(3.5)) + 2.5, which is 5.5. Use parenthesis to cast an arithmetic expression. For example: (int)(3.5+2.5) becomes 6.