Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a positive value becomes negative after casting byte in Java?

Tags:

java

casting

public class Test1 {

    public static void main(String[] args) {

        byte b1=40;
        byte b=(byte) 128;

        System.out.println(b1);
        System.out.println(b);
    }
}

the output is

40
-128

the first output is 40 I understood but the second output -128 How it is possible ? is it possible due to it exceeds its range ? if yes how it works after byte casting...help me

like image 320
rajeev Avatar asked Sep 12 '13 02:09

rajeev


People also ask

How do you change positive to negative in Java?

To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.

Can a byte be negative Java?

In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 .

Can byte store negative values?

In C#, a byte represents an unsigned 8-bit integer, and can therefore not hold a negative value (valid values range from 0 to 255 ).

How do you negate a value in Java?

negate() method returns a BigDecimal whose value is the negated value of the BigDecimal with which it is used. Parameters: The method does not take any parameters . Return Value: This method returns the negative value of the BigDecimal object and whose scale is this.


1 Answers

When you cast 128 (10000000 in binary) to an eight-bit byte type, the sign bit gets set to 1, so the number becomes interpreted as negative. Java uses Two's Complement representation, so 10000000 is -128 - the smallest negative number representable with 8 bits.

Under this interpretation, 129 becomes -127, 130 becomes -126, and so on, all the way to 255 (11111111 in binary), which becomes -1.

like image 155
Sergey Kalinichenko Avatar answered Oct 25 '22 06:10

Sergey Kalinichenko