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
To convert positive int to negative and vice-versa, use the Bitwise Complement Operator.
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 .
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 ).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With