JAVA Syllabus
QUESTIONS & ANSWERS

How are positive and negative numbers represented internally in java?

In Java, positive and negative numbers are represented internally using a system called two's complement.

In two's complement, the most significant bit (leftmost bit) of a binary number is used to represent the sign of the number. If the most significant bit is 0, then the number is positive, and if it is 1, the number is negative.

To represent negative numbers, two's complement is used to flip all the bits in the positive version of the number and add 1.

For example: 

Decimal 5           = 0000 0101 (binary)
1's complement = 1111 1010 (changes 0 to 1 and vice-versa)
(add 1 to 1's
complement)                      +1 
                             --------------
2's complement = 1111 1011 (Decimal -5)

 

Java uses 32 bits to represent integer numbers, which means that the most significant bit represents the sign of the number. The remaining 31 bits represent the magnitude of the number. Therefore, the range of integer numbers that can be represented in Java is from -2^31 to 2^31-1.

03/03/2023, 11:45 am Read : 304 times