# 2’s complement – Binary representation of Negative numbers in Java

Hey there!

Welcome to ClearUrDoubt.com.

In this post, we will look at how a negative number is represented in binary format in Java.

All the integer types in Java are signed integers i.e., they represent both positive and negative numbers. Java uses the encoding “2’s complement” to represent negative numbers.

How to find the 2’s complement of a negative number:

To represent -24,

• consider the binary format of its positive number(24) i.e., 00011000.
• Invert all the digits in it which returns the 1’s complement of the number. i.e., 11100111
• Add 1 to the 1’s complement value. 11100111 + 1 = 11101000 (is the 2’s complement representation of -24)

2’s complement is used to overcome the issue of “Zero Crossing“. Assuming a byte value, zero is represented by 00000000. In 1’s complement, simply inverting all of the bits creates 11111111, which creates negative zero. The trouble is that negative zero is invalid in integer math. This problem is solved by using two’s complement to represent negative values. When using two’s complement, 1 is added to the complement, producing 100000000. This produces a 1 bit too far to the left to fit back into the byte value, resulting in the desired behavior, where –0 is the same as 0, and 11111111 is the encoding for –1.

Source: Java: The Complete Reference

Happy Learning :).