Course contentsShow
← Java
Lesson 118 of 2,8703. Operators and ExpressionsFree lesson

The Bitwise NOT Operator (~)

How ~ inverts all bits in a value, including the sign bit.

The Bitwise NOT Operator (~)

What you'll learn: How the bitwise NOT operator inverts every single bit in a number, including the sign bit.

What Does ~ Do?

The bitwise NOT operator (~) is a unary operator that flips every bit in its operand: every 0 becomes 1, and every 1 becomes 0. This includes the sign bit (the leftmost bit in two's complement representation), which means ~ often produces surprising results for beginners.

How It Works

Think of ~ as a universal inverter—like flipping a row of light switches. If all the lights were on (1), they all turn off (0), and vice versa.

For example, consider the byte value 5:

00000101  (binary representation of 5)

Applying ~ inverts every bit:

11111010  (result after ~)

Since Java uses two's complement for signed integers, and the leftmost bit is now 1, this result represents a negative number: -6.

Why the Strange Result?

In two's complement arithmetic, ~n always equals -n - 1. So:

  • ~5 equals -6
  • ~0 equals -1
  • ~-1 equals 0

This happens because flipping all bits is mathematically equivalent to negating and subtracting one.

Basic Example

int a = 5;
int result = ~a;  // result is -6

int b = -1;
int inverted = ~b;  // inverted is 0

Key Takeaway: The bitwise NOT operator (~) inverts all bits in a value, turning 0s to 1s and 1s to 0s. Because it flips the sign bit too, ~n always produces -n - 1 for any integer n.