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

Introduction to Bitwise Operations

Understanding bits, binary representation, and why bitwise operations exist in Java.

Introduction to Bitwise Operations

What you'll learn: You'll discover what bits are, how computers represent numbers in binary, and why Java includes special operators for working directly with individual bits.

What Are Bits?

At the lowest level, computers store all data as bits—binary digits that are either 0 or 1. When you declare an int in Java, it's stored as 32 bits. For example, the number 5 in decimal is 00000000000000000000000000000101 in binary (we typically show just 101 for simplicity).

Every primitive type you've learned—int, long, byte, char, boolean—is ultimately a pattern of bits in memory.

Binary Representation

Binary is a base-2 number system. Each position represents a power of 2:

  • 1 (binary) = 1 (decimal)
  • 10 (binary) = 2 (decimal)
  • 101 (binary) = 5 (decimal): (1×4) + (0×2) + (1×1)
  • 1111 (binary) = 15 (decimal): (1×8) + (1×4) + (1×2) + (1×1)

Think of it like a row of light switches: each switch is either on (1) or off (0), and the combination represents a number.

Why Bitwise Operations Exist

Java provides bitwise operators that let you manipulate individual bits within a number. While arithmetic operators like + and - work with whole numbers, bitwise operators work at the bit level.

These operations are useful for:

  • Low-level programming (device drivers, graphics)
  • Performance optimization in specific algorithms
  • Representing multiple flags or settings in a single integer
  • Understanding how data is actually stored

You've already seen operators for arithmetic (+, -) and logic (&&, ||). Bitwise operators are similar but operate on the binary representation of numbers directly.

Key Takeaway: Bitwise operations manipulate the individual binary digits (bits) that make up integers, providing a way to work with data at the most fundamental level computers understand.