Source Code |
public class Conversions { public static void main(String[] args) { int i = 200; byte b = 10; int j = b; // 1 byte c = (byte)i; // 2 System.out.println(j); System.out.println(c); } } // Output 10 -56 |
Source Code |
public class HardwareTester { public static void main(String[] args) { byte input1 = readByteFromHardware(); byte input2 = readByteFromHardware(); byte xorTotal = input1 ^ input2; // Do some more processing using xorTotal } private static byte readByteFromHardware() { // Reads a byte of data from the hardware and returns it. // For the sake of this example, assume this method // is complete and returns a value. } } |
HardwareTest.java:8: possible loss of precision found : int required: byte byte xorTotal = input1 ^ input2; ^So, the question is, why is the compiler complaining about a narrowing conversion at this point? Notice that it says you're trying to convert an int to a byte. Certainly, converting an int to a byte is a narrowing conversion, but where the heck did the int come from? There isn't an int anywhere in that code!
Source Code |
public class ImplicitExplicitCast { public static void main(String[] args) { byte b1 = -13; b1 >>>= 1; System.out.println(b1); } } |
Source Code |
public class ImplicitExplicitCast { public static void main(String[] args) { byte b1 = -13; b1 = (byte)(b1 >>> 1); System.out.println(b1); } } |