Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0087 Automatic promotions can cause compile-time errors

public class Main { public static void main(String[] argv) { byte b = 5; b = b * 2; // Error! Cannot assign an int to a byte! } } Compiling the code above generates the following errors: D:\>javac Main.java Main.java:4: possible loss of precision found : int required: byte b = b * 2; // Error! Cannot assign an int to a byte! ^ 1 error If you understand the consequences of overflow, use an explicit cast. public class Main { public static void main(String[] argv) { byte b = 50; b = (byte) (b * 2); System.out.println("b is " + b); } } The output from the code above is: b is 100