Every literal integer in Java is implicitly of type int by default. Also, any operation done with literal integer operands results to int by default. So the following code will be fine and will definitely compile:
byte b = 5; //byte is made up of 8 bits and int with 32 bits
because the compiler implicitly puts a casting to it like this:
byte b = (byte) 5;
But this won’t compile:
byte a = 5;
byte b = 2;
byte c = a + b;
because any operation done with literal integer operands always have the result of type int by default and the compiler thinks about loss of precision without explicit casting. So to make the above code compile, we put an explicit cast like this:
byte a = 5;
byte b = 2;
byte c = (byte) a + b;
which is like telling the compiler that “Don’t worry, I know what I am doing and am aware about the possible loss of precision thing.”. 😀