Casting type primitives

I am a beginner in Java. I cannot figure this line even after trying for a long time.

byte num = (byte) 135;

this line gives the result -121, why is it in the signed number?

Can anyone develop it?

+3


source to share


1 answer


In Java byte

, they are always signed, and they range from -128

to 127

. When the int

literal is 135

off before byte

, the result is a negative number because the 8th bit is set.

 1000 0111

      

Specifically, the JLS, section 5.1.3 , says:



Narrowing the conversion from a signed integer to an integral type T simply discards all but the n least significant bits, where n is the number of bits used to represent the type T. value will differ from the sign of the input value.

When you create a literal int

like 135

on byte

, it is a narrowing of the primitive conversion.

+8


source







All Articles