in java, the following program shows error in the line 10 as precision loss.... can anyone explain how is it so?? class c4 { public static void main(String [] args) { byte b1=33; b1++; byte b2=55; b2=b1+1; System.out.println(b1+""+b2); } }
Well, I don't know much about Java, but here's a general explanation: A precision loss occurs when a value of a 'higher' precision type is converted to a 'lower' precision type. Like for example, converting from a float to integer, or from integer to byte. So my guess is that in line 10 (the println) a process occurs that converts the byte into a lower precision type. Does Java has any value type that has a lower precision than byte though?
precission loss is due to the error in conversion from int to byte at line b2=b1+1; // it is taking result of b1+1 as integer and you are trying to store it in a byte variable and this is not possible because you need to explicitly type cast the value as i have shown it below b2=(byte) (b1+1); this will help you remove your error
then how does the incrementer works does it increment the byte type as byte.... or does it convert it to int and then restore it??? does it make any difference in using ++ and +1
yes it is incrementing it as byte
no it does not make any difference in doing ++ or +1
Besides, if it converts the value to int and then converts it back, there wouldn't be any problems at all, as it would use an explicit conversion.
Join our real-time social learning platform and learn together with your friends!