public class TestEmployee {
public static void main(String args[]) {
byte b=(byte)1*200;
System.out.println(b);
}
}
I have written above simple code. But I am getting folowing error "Possible loss of precision"
As of my knowledge, when we perform integer calculations , the operands are converted to int and then the calculation in performed. And final result is in int. Now as the range of byte data type is (-128 to 127) the above calculatio开发者_StackOverflow社区ns falls out of range of byte. So I downcast it to byte. Then why I am getting the error.
Please help and correct my concepts of casting..
You are casting the 1
to a byte, not the result of 1*200
. So you want to use
byte b = (byte)(1*200);
in this case.
your code should go like this....just missing the brackets before the multiplication operation otherwise only 1 will be downcast and 200 remains as integer
public class TestEmployee {
public static void main(String args[])
{ byte b=(byte) ( 1 * 200);
System.out.println(b);
}
}
You haven't put 1 * 200
in brackets. It should be byte b = (byte)(1 * 200).
Otherwise you do byte b = 200
which is an int and you get an error.
You are missing the parenthesis ()
while downcasting.
Change like this,
byte b=(byte)(1*200);
When you write like this,
byte b=(byte)1*200;
^
`compilation error : possible loss of precision`
It is because it tries to convert an int : 200
to byte which will result in compilation error.
精彩评论