- Bitwise and BitShift Operators in Java — AND, OR, XOR, Signed Left and Right shift Operator Examples
- 1. Bit and Byte Basics
- Bitwise and operators in java
- Java Bitwise and Shift Operators
- 1. Java Bitwise OR Operator
- Example 1: Bitwise OR
- 2. Java Bitwise AND Operator
- Example 2: Bitwise AND
- 3. Java Bitwise XOR Operator
- Example 4: Bitwise XOR
- 4. Java Bitwise Complement Operator
- 2’s Complement
- Example 3: Bitwise Complement
- Java Shift Operators
- 5. Java Left Shift Operator
- Example 5: Left Shift Operators
- 5. Java Signed Right Shift Operator
- Example 6: Signed Right Shift Operator
- 7. Java Unsigned Right Shift Operator
- Example 7: UnSigned Right Shift
- Table of Contents
- A quick guide to bitwise operators in Java
- Be ready for any bit manipulation question
- What is bit manipulation?
- Bitwise Manipulation and Coding Interviews
- Bitwise Operators
- AND Operator
Bitwise and BitShift Operators in Java — AND, OR, XOR, Signed Left and Right shift Operator Examples
Bitwise and Bit Shift Operators in Java are a powerful set of operators that allows you to manipulate bits on integral types like int, long, short, bytes, and boolean data types in Java. Bitwise and Bit shift operator is among the fastest operator in Java but still, many Java programmers don’t familiar with bitwise and bitshift operations, especially those who don’t come from C programming backgrounds. If you have already learned C or C++ before starting with Java then understanding bitwise and bitshift operators are quite easy in Java, because it’s similar to the bitwise operation in C.
Some of th e tricky programming interview questions e .g. checking if a number is power of tw o or swapping two numbers without temporary variable or, can be easily solved using bitwise operators.
This Java programming tutorial is a quick recap of different bitwise operator available in Java and how to use them. This tutorial also discusses bit shift operators, both signed and unsigned for example.
1. Bit and Byte Basics
Before exploring bitwise and bit shift operator in Java, its prerequisite that you must be familia r with binary format, bits, bytes and bit wise operations like AND, OR, XOR, NOT etc. Knowledge of binary arithmetic is also important to understand code written using bitwise operators in Java programming language.
Bitwise and operators in java
«Очень интересно» . Только НЕПОНЯТНО. Зачем это нужно? Хорошо, что у нас есть Гугл, который говорит: Побитовые операции пременяются для быстрого выполнения вычислений и меньшего потребления ресурсов, связанных с этими вычислениями. Если б с этих слов начиналась статья, дальше уже хоть 100 страниц текста, читались бы на релаксе.
https://javarush.com/quests/lectures/questsyntaxpro.level08.lecture06 вот в этой лекции из квеста javarush сказано, что не все операции выполняются с лева на право, а например унарные операции выполняются с права на лево, а тут пишут — «Все операции выполняются слева направо, однако с учетом своего приоритета.» кто ошибается, подскажите пожалуйста))
Для чего нужны Сдвиги влево и в право? хоть бы один реальный пример из программы выполняющей конкретную задачу
Замечательно написано! Освежила в памяти знания, все просто понятно логично и подробно. Александр, спасибо за лекцию!
JavaRush — это интерактивный онлайн-курс по изучению Java-программирования c нуля. Он содержит 1200 практических задач с проверкой решения в один клик, необходимый минимум теории по основам Java и мотивирующие фишки, которые помогут пройти курс до конца: игры, опросы, интересные проекты и статьи об эффективном обучении и карьере Java‑девелопера.
Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.
Java Bitwise and Shift Operators
In Java, bitwise operators perform operations on integer data at the individual bit-level. Here, the integer data includes byte , short , int , and long types of data.
There are 7 operators to perform bit-level operations in Java.
1. Java Bitwise OR Operator
The bitwise OR | operator returns 1 if at least one of the operands is 1. Otherwise, it returns 0.
The following truth table demonstrates the working of the bitwise OR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.
The above table is known as the «Truth Table» for the bitwise OR operator.
Let’s look at the bitwise OR operation of two integers 12 and 25.
12 = 00001100 (In Binary) 25 = 00011001 (In Binary) Bitwise OR Operation of 12 and 25 00001100 | 00011001 ____________ 00011101 = 29 (In Decimal)
Example 1: Bitwise OR
2. Java Bitwise AND Operator
The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it returns 0.
The following table demonstrates the working of the bitwise AND operator. Let a and b be two operands that can only take binary values i.e. 1 and 0.
Let’s take a look at the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary) 25 = 00011001 (In Binary) // Bitwise AND Operation of 12 and 25 00001100 & 00011001 ____________ 00001000 = 8 (In Decimal)
Example 2: Bitwise AND
3. Java Bitwise XOR Operator
The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both the operands are 0 or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.
Let’s look at the bitwise XOR operation of two integers 12 and 25.
12 = 00001100 (In Binary) 25 = 00011001 (In Binary) // Bitwise XOR Operation of 12 and 25 00001100 ^ 00011001 ____________ 00010101 = 21 (In Decimal)
Example 4: Bitwise XOR
4. Java Bitwise Complement Operator
The bitwise complement operator is a unary operator (works with only one operand). It is denoted by ~ .
It changes binary digits 1 to 0 and 0 to 1.
It is important to note that the bitwise complement of any integer N is equal to — (N + 1). For example,
Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36. Now let’s see if we get the correct answer or not.
35 = 00100011 (In Binary) // using bitwise complement operator ~ 00100011 __________ 11011100
In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we convert the result into decimal we get 220.
However, it is important to note that we cannot directly convert the result into decimal and get the desired output. This is because the binary result 11011100 is also equivalent to -36.
To understand this we first need to calculate the binary output of -36.
2’s Complement
In binary arithmetic, we can calculate the binary negative of an integer using 2’s complement.
1’s complement changes 0 to 1 and 1 to 0. And, if we add 1 to the result of the 1’s complement, we get the 2’s complement of the original number. For example,
// compute the 2's complement of 36 36 = 00100100 (In Binary) 1's complement = 11011011 2's complement: 11011011 + 1 _________ 11011100
Here, we can see the 2’s complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise complement of 35.
Hence, we can say that the bitwise complement of 35 is -(35 + 1) = -36.
Example 3: Bitwise Complement
Java Shift Operators
There are three types of shift operators in Java:
5. Java Left Shift Operator
The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by
As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.
As a result, the left-most bit (most-significant) is discarded and the right-most position(least-significant) remains vacant. This vacancy is filled with 0s.
Example 5: Left Shift Operators
5. Java Signed Right Shift Operator
The signed right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >> .
When we shift any number to the right, the least significant bits (rightmost) are discarded and the most significant position (leftmost) is filled with the sign bit. For example,
// right shift of 8 8 = 1000 (In Binary) // perform 2 bit right shift 8 >> 2: 1000 >> 2 = 0010 (equivalent to 2)
Here, we are performing the right shift of 8 (i.e. sign is positive). Hence, there no sign bit. So the leftmost bits are filled with 0 (represents positive sign).
// right shift of -8 8 = 1000 (In Binary) 1's complement = 0111 2's complement: 0111 + 1 _______ 1000 Signed bit = 1 // perform 2 bit right shift 8 >> 2: 1000 >> 2 = 1110 (equivalent to -2)
Here, we have used the signed bit 1 to fill the leftmost bits.
Example 6: Signed Right Shift Operator
class Main < public static void main(String[] args) < int number1 = 8; int number2 = -8; // 2 bit signed right shift System.out.println(number1 >> 2); // prints 2 System.out.println(number2 >> 2); // prints -2 > >
7. Java Unsigned Right Shift Operator
Java also provides an unsigned right shift. It is denoted by >>> .
Here, the vacant leftmost position is filled with 0 instead of the sign bit. For example,
// unsigned right shift of 8 8 = 1000 8 >>> 2 = 0010 // unsigned right shift of -8 -8 = 1000 (see calculation above) -8 >>> 2 = 0010
Example 7: UnSigned Right Shift
class Main < public static void main(String[] args) < int number1 = 8; int number2 = -8; // 2 bit signed right shift System.out.println(number1 >>> 2); // prints 2 System.out.println(number2 >>> 2); // prints 1073741822 > >
As we can see the signed and unsigned right shift operator returns different results for negative bits. To learn more visit the Difference between >> and >>>.
Table of Contents
A quick guide to bitwise operators in Java
Bit manipulation is the direct manipulation of data bits to perform operations and is an important optimization skill now tested by FAANG recruiters. However, this topic is heavily mathematical and is rarely covered in a non-university computer science setting.
Today, we’ll give you a tutorial on bit manipulation and explore some hands-on practice with popular interview questions.
Here’s what we’ll cover today:
Be ready for any bit manipulation question
Practice top asked questions for each bitwise operator with hands-on coding environments.
What is bit manipulation?
Bit manipulation is the process of applying logical operations on a sequence of bits, the smallest form of data in a computer, to achieve a required result. Bit manipulation has constant time complexity and process in parallel, meaning it is very efficient on all systems.
Most programming languages will have you work with abstractions, like objects or variables, rather than the bits they represent. However, direct bit manipulation is needed to improve performance and reduce error in certain situations.
Bit manipulation requires a strong knowledge of binary and binary conversion.
Here’s a few examples of tasks that require bit manipulation:
- Low-level device control
- Error detection and correction algorithms
- Data compression
- Encryption algorithms
- Optimization
For example, take a look at the difference between an arithmetic and bit manipulation approach to finding the green portion of an RGB value:
While both do the same thing, the second option is considerably faster, as it works directly within memory rather than through a level of abstraction.
We’ll explore what each of these operators do later in this article ( >> and & ).
Bitwise Manipulation and Coding Interviews
Bit manipulation is also a common topic in coding interviews, especially with FAANG companies. These interviewers expect you to have a basic understanding of bits, fundamental bit operators, and generally understand the thought process behind bit manipulation.
Having this knowledge demonstrates that you’re a well-rounded developer who understands both the specific tools and the foundation of computer science.
If you’re applying for a role that will work with embedded systems or other low-level systems, you’ll encounter more bit questions. In short, the closer your role is to machine level, the more bit manipulation questions you’ll encounter.
The best way to prepare for bit manipulation questions is to practice using each bitwise operator and brush up on your binary to decimal conversions.
Bitwise Operators
Bitwise operations take one or more bit patterns or binary numerals and manipulate them at the bit level. They’re essentially our tool to manipulate bits to achieve our operations.
While arithmetic operations perform operations on human-readable values ( 1+2 ), bitwise operators manipulate the low-level data directly.
- They are fast and simple actions.
- They are directly supported by the processor.
- They are used to manipulate values for comparisons and calculations.
- Bitwise operations are incredibly simple and faster than arithmetic operations.
Let’s take a quick look at each of the major Bitwise operators and their uses.
Enjoying the article? Scroll down to sign up for our free, bi-monthly newsletter.
AND Operator
AND ( & ) is a binary operator that compares two operands of equal length. The operands are converted from their readable form to binary representation. For each bit, the operation checks if both bits are 1 across both operands. If yes, that bit is set to 1 in the answer. Otherwise, the corresponding result bit is set to 0.
It essentially multiplies each bit by the corresponding bit in the other operand. As multiplying anything by 0 results in 0 , the AND comparison with any 0 bit will result in 0 .
- If two input bits are 1, the output is 1.
- In all other cases its 0, for example:
- 1 & 0 => yields to 0.
- 0 & 1 => yields to 0.
- 0 & 0 => yields to 0.
0101 (decimal 5) AND 0011 (decimal 3)
The operation may be used to determine whether a particular bit is set (1) or clear (0). It’s also used to clear selected bits of a register in which each bit represents an individual Boolean state.