Bitwise Operators in Java

Bitwise Operators in Java

In the Java programming language, several bitwise operators are defined. These operators are applied to integer data types, such as byte, short, int, long, and char.

List of Bitwise Operators

  • & — bitwise AND (AND)
  • | — bitwise OR (OR)
  • ^ — bitwise XOR (XOR)
  • ~ — bitwise NOT (NOT)
  • << — left shift
  • >> — right shift
  • >>> — right shift with zero fill
Bitwise operators perform operations on each bit of the numbers individually.

Example

 int a = 55; 
int b = 24; 
System.out.println(Integer.toBinaryString(a)); // 110111 
System.out.println(Integer.toBinaryString(b)); // 11000 

After conversion to binary code:

 a = 110111 b = 011000 

Bitwise AND (&)

The operator & (AND) returns 1 in the bit where both operands have the bit 1. Otherwise, it returns 0.

Example:

 int result = a & b; 
System.out.println(Integer.toBinaryString(result)); // 10000 
System.out.println(result); // 16 

Step-by-step explanation:

Operand Bits
a = 55 110111
b = 24 011000
a & b 010000

The result is the binary number 010000, which is equal to 16 in decimal.

Bitwise OR (|)

The operator | returns 1 in the bit position where at least one of the operands has the bit 1.

 int result = a | b; 
System.out.println(Integer.toBinaryString(result)); // 111111 System.out.println(result); // 63 
Operand Bits
a = 55 110111
b = 24 011000
a | b 111111

Result: 111111 = 63.

Bitwise Exclusive OR (^)

The operator ^ (XOR) returns 1 in the bit position where the bits differ, and 0 where they are the same.

 int result = a ^ b; 
System.out.println(Integer.toBinaryString(result)); // 101111 System.out.println(result); // 47 
Operand Bits
a = 55 110111
b = 24 011000
a ^ b 101111

Result: 101111 = 47.

Bitwise NOT (~)

The operator ~ inverts all bits of a number — all 1 become 0, and vice versa.

 int a = 55; 
System.out.println(Integer.toBinaryString(~a)); // ...the result will be in two's complement System.out.println(~a); // -56 
In bitwise negation, Java uses the representation of numbers in two's complement, so the result is negative.

Bitwise Shifts

  • << — shifts bits to the left, filling with zeros on the right (multiplication by 2 to the power of N)
  • >> — shifts bits to the right, preserving the sign (division by 2 to the power of N)
  • >>> — shifts to the right, filling with zeros (regardless of the sign)

Example:

 int a = 8; 
System.out.println(a << 2); // 32 (8 * 2^2) 
System.out.println(a >> 1); // 4 (8 / 2^1) 
System.out.println(a >>> 1); // 4 (the same result for positive numbers) 

Homework

  1. Create two variables int a and int b with different values.
  2. Output their binary representation using Integer.toBinaryString().
  3. Apply all bitwise operators to them: &, |, ^, ~, <<, >>, >>>.
  4. For each result, display both binary and decimal forms.
  5. Try to explain why you obtained such results.

Test — How well did you understand the lesson?


🌐 in English
Всего лайков:0

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Slice internals в Go ↔ Java: от заголовка до скрытых аллокаций
Slice в Go — это одна из тех структур, которая выглядит простой, но под капотом ведёт себя как маленький хитрый зверь. Если ты Java-разработчик, ты можешь думать: «ну это же просто ArrayList». И вот з...
Разбираем: Rate‑limiter, non‑blocking operations, scheduler  Go vs Java | Concurrency часть 4
Эта статья посвящена пониманию принципов работы с конкурентностью и синхронизацией в Go и Java. Мы рассмотрим ключевые подходы, такие как rate‑limiter, неблокирующие операции и планирование задач, сра...
Memory / Runtime / Allocator - Go vs Java
Управление памятью, указатели и профилирование — это фундаментальные аспекты эффективного кода. Рассмотрим три ключевых концепта: slice backing array, pointer и профилирование (pprof / trace), и сравн...

Новые статьи:

Конкурентность — это не про «запустить много потоков». Это про договорённости между ними. Представь кухню ресторана: — повара (потоки / горутины) — заказы (задачи) — и главный вопрос: как они коорди...
История начинается не с академической теории, а с типичной production-проблемы. Представьте сервис: 48 CPU 300+ потоков нагрузка 200k операций в секунду много shared state Команда использует обы...
Когда HashMap начинает убивать продакшн: инженерная история ConcurrentHashMap
Представьте обычный продакшн-сервис. 32 CPU сотни потоков кэш конфигурации / сессий / rate limits десятки тысяч операций в секунду И где-то внутри — обычный Map. Сначала всё выглядит безобидно. Map&...
Fullscreen image