Ahsan Rafiq
Ahsan Rafiq

Reputation: 111

Casting of primitives type

I am beginner in Java. I cannot understand this line even after a long try.

byte num=(byte)135;

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

Can any one elaborate it ?

Upvotes: 3

Views: 73

Answers (1)

rgettman
rgettman

Reputation: 178253

In Java, bytes are always signed, and they are in the range -128 to 127. When the int literal 135 is downcasted to a byte, the result is a negative number because the 8th bit is set.

 1000 0111

Specifically, the JLS, Section 5.1.3, states:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

When you cast an int literal such as 135 to a byte, that is a narrowing primitive conversion.

Upvotes: 8

Related Questions