Operators in Java
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the
functionality they provide. Some of the types are:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
1. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• - : Subtraction
// Addition
// Subtraction
// Multiplication
// Division
// Modulo
}
Output
Addition: 30
Subtraction: -10
Multiplication: 200
Division: 0
Modulo: 10
Explanation:
• Division (/) truncates the decimal portion when used with integers.
2. Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a
value.
• + : Unary plus indicates the positive value (numbers are positive without this, however). It performs an
automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary
numeric promotion.
• ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
o Post-Increment: Value is first used for computing the result and then incremented.
• -- : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement
operators.
o Post-decrement: Value is first used for computing the result and then decremented.
3. Assignment Operator: '=' Assignment operator is used to assigning a value to any variable. It has a right to left
associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and
therefore right-hand side value must be declared before using it or should be a constant.
variable = value;
In many cases, the assignment operator can be combined with other operators to build a shorter version of the
statement called a Compound Statement. For example, instead of a = a+5, we can write a += 5.
• +=, for adding left operand with right operand and then assigning it to the variable on the left.
• -=, for subtracting right operand from left operand and then assigning it to the variable on the left.
• *=, for multiplying left operand with right operand and then assigning it to the variable on the left.
• /=, for dividing left operand by right operand and then assigning it to the variable on the left.
• %=, for assigning modulo of left operand by right operand and then assigning it to the variable on the left.
// Simple assignment
x = y; // x is now 5
// Compound assignments
x += y; // x = x + y
x -= y; // x = x - y
x *= y; // x = x * y
x /= y; // x = x / y
Output
After assignment: 5
Explanation:
• +=, -=, *=, and /= combine arithmetic and assignment in one operation.
4. Relational Operators: These operators are used to check for relations like equality, greater than, and less than.
They return boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is,
o ==, Equal to returns true if the left-hand side is equal to the right-hand side.
o !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
o <, less than: returns true if the left-hand side is less than the right-hand side.
o <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
o >, Greater than: returns true if the left-hand side is greater than the right-hand side.
o >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-
hand side.
// Equal to
// Not equal to
// Greater than
// Less than
Output
Explanation:
• Relational operators return boolean values (true or false) based on the comparison.
5. Logical Operators: These operators are used to perform "logical AND" and "logical OR" operations, i.e., a function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for
making a decision. Java also has "Logical NOT", which returns true when the condition is false and vice-versa
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
// Logical AND
// Logical OR
// Logical NOT
// Short-circuiting example
int x = 10, y = 5;
Output
Explanation:
• Short-circuiting skips the second condition if the first condition determines the result.
6. Ternary operator: Ternary operator is a shorthand version of the if-else statement. It has three operands and
hence the name ternary.
The above statement means that if the condition evaluates to true, then execute the statements after the '?' else
execute the statements after the ':'.
// Java program to illustrate
// ternary operator.
// numbers
result
+ result);
Output
7. Bitwise Operators: These operators are used to perform the manipulation of individual bits of a number. They can
be used with any of the integer types. They are used when performing update and query operations of the Binary
indexed trees.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns the one's complement
representation of the input value, i.e., with all bits inverted.
8. Shift Operators: These operators are used to shift the bits of a number left or right, thereby multiplying or dividing
the number by two, respectively. They can be used when we have to multiply or divide a number by two. General
format-
• <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as multiplying the number with some power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result.
The leftmost bit depends on the sign of the initial number. Similar effect as dividing the number with some
power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a
result. The leftmost bit is set to 0.
1. Precedence and Associativity: There is often confusion when it comes to hybrid equations which are equations
having multiple operators. The problem is which part to solve first. There is a golden rule to follow in these situations.
If the operators have different precedence, solve the higher precedence first. If they have the same precedence,
solve according to associativity, that is, either from right to left or from left to right. The explanation of the below
program is well written in comments within the program itself.
// (* = / = %) > (+ = -)
// prints a+(b/d)
System.out.println("a+b*d-e/f = "
+ (a + b * d - e / f));
}
Output
a+b/d = 20
a+b*d-e/f = 219
2. Be a Compiler: Compiler in our systems uses a lex tool to match the greatest match when generating tokens. This
creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too many of the readers
might seem to create a compiler error. But this statement is absolutely correct as the token created by lex are a, =, b,
++, +, c. Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly,
a=b+++++c; would generate an error as tokens generated are a, =, b, ++, ++, +, c. which is actually an error as there is
no operand after the second unary operand.
class GfG {
// a=b+++c is compiled as
// b++ +c
a = b++ + c;
// a=b+++++c is compiled as
// b++ ++ +c
// a=b+++++c;
// System.out.println(b+++++c);
Output
3. Using + over (): When using + operator inside system.out.println() make sure to do addition using parenthesis. If
we write something before doing addition, then string addition takes place, that is, associativity of addition is left to
right, and hence integers are added to a string first producing a string, and string objects concatenate when using +.
Therefore it can create unwanted results.
class GfG {
int x = 5, y = 8;
// concatenates x and y as
// addition of x and y
Output
Concatenation (x+y)= 58
Addition (x+y) = 13
Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any
integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary
indexed trees.
1. Bitwise OR (|)
This operator is a binary operator, denoted by '|'. It returns bit by bit OR of input values, i.e., if either of the bits is 1,
it gives 1, else it shows 0.
Example:
This operator is a binary operator, denoted by '&.' It returns bit by bit AND of input values, i.e., if both bits are 1, it
gives 1, else it shows 0.
Example:
This operator is a binary operator, denoted by '^.' It returns bit by bit XOR of input values, i.e., if corresponding bits
are different, it gives 1, else it shows 0.
Example:
This operator is a unary operator, denoted by '~.' It returns the one's complement representation of the input value,
i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0.
Example:
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2's complement of that number, i.e., 2's complement of 10 will be -6.
// bitwise operators
class GfG {
// Initial values
int a = 5;
int b = 7;
// bitwise and
// bitwise or
// 0101 | 0111=0111 = 7
// bitwise xor
// 0101 ^ 0111=0010 = 2
// bitwise not
// assignment
// a=a&b
a &= b;
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};
// bitwise or
int c= a | b;
// bitwise and
int d= a & b;
// bitwise xor
int e= a ^ b;
// bitwise not
System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println("~a= "+binary[g]);
Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a= 1100
Shift operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two,
respectively. They can be used when we have to multiply or divide a number by two.
Syntax:
Note: For more detail about the Shift Operators in Java, refer Shift Operator in Java.
The left shift operator (<<) is a bitwise operator that shifts the bits of a number to the left by a specified number of
positions. It effectively multiplies the number by 2 raised to the power of the specified shift count. This operator is
often used for low-level programming, bit manipulation, and performance optimization.
int x = 3;
// Shift left by 1
// Shift left by 2
Output
12
Explanation:
• When 3 (binary 0000 0011) is shifted left by 1, the result is 6 (binary 0000 0110).
int x = 3;
int y = 4;
System.out.println(z);
Output
48
Explanation:
int x = -1;
// Shift left by 1
Output
-2
Explanation:
• The value -1 is represented in binary as all 1s (1111 1111 in 8-bit 2's complement representation).
• The sign bit (leftmost bit) remains 1 for negative numbers, maintaining the number's sign.
In C/C++ there is only one right shift operator '>>' which should be used only for positive integers or unsigned
integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for
negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators.
In Java, the operator '>>' is signed right shift operator. All integers are signed in Java, and it is fine to use >> for
negative numbers. The operator '>>' uses the sign bit (leftmost bit) to fill the trailing positions after the shift. If the
number is negative, then 1 is used as a filler and if the number is positive, then 0 is used as a filler. For example, if the
binary representation of a number is 10....100, then right shifting it by 2 using >> will make it 11.......1.
Example:
// Main class
class GfG {
// Main driver method
int x = -4;
int y = 4;
Output
-2
Explanation:
o Decimal value: 2.
In Java, the operator '>>>' denotes unsigned right shift operator and always fill 0 irrespective of the sign of the
number.
Example:
// Main class
class GfG {
int x = -1;
Output
Explanation:
o Decimal value: 7.
o Decimal value: 3.
o Decimal value: 1.