Table of contents
1.
Introduction
2.
Arithmetic Operators
2.1.
Addition (+)
2.1.1.
Example
2.2.
Subtraction (-)
2.2.1.
Example
2.3.
Multiplication (*)
2.3.1.
Example
2.4.
Division (/)
2.4.1.
Example
2.5.
Modulus (%)
2.5.1.
Example
3.
Unary Operators
3.1.
Increment (++)
3.1.1.
Example
3.2.
Decrement (--)
3.2.1.
Example
3.3.
Unary plus (+)
3.3.1.
Example
3.4.
Unary minus (-)
3.4.1.
Example
3.5.
Logical NOT (!)
3.5.1.
Example
4.
Assignment Operator
4.1.
Example
5.
Compound assignment operators include:
5.1.
Addition assignment (+=)
5.1.1.
Example
5.2.
Subtraction assignment (-=)
5.2.1.
Example
5.3.
Multiplication assignment (*=)
5.3.1.
Example
5.4.
Division assignment (/=)
5.4.1.
Example
5.5.
Modulus assignment (%=)
5.5.1.
Example
6.
Relational Operators
6.1.
Equal to (==)
6.1.1.
Example
6.2.
Not equal to (!=)
6.2.1.
Example
6.3.
Greater than (>)
6.3.1.
Example
6.4.
Less than (<)
6.4.1.
Example
6.5.
Greater than or equal to (>=)
6.5.1.
Example
6.6.
Less than or equal to (<=)
6.6.1.
Example
7.
Logical Operators
7.1.
Logical AND (&&)
7.1.1.
Example
7.2.
Logical OR (||)
7.2.1.
Example
7.3.
Logical NOT (!)
7.3.1.
Example
8.
Ternary Operator
8.1.
Example
8.2.
Example
9.
Bitwise Operators
9.1.
Bitwise AND (&)
9.1.1.
Example
9.2.
Bitwise OR (|)
9.3.
Bitwise XOR (^)
9.3.1.
Example
9.4.
Bitwise complement (~)
9.4.1.
Example
9.4.2.
Example:
10.
Shift Operators
10.1.
Left shift (<<)
10.1.1.
Example
10.2.
Signed right shift (>>)
10.2.1.
Example
10.3.
Unsigned right shift (>>>)
10.3.1.
Example
11.
Frequently Asked Questions
11.1.
What is the difference between the logical AND (&&) and the bitwise AND (&) operator?
11.2.
Can the ternary operator be nested?
11.3.
What happens if you try to divide an integer by zero using the division operator?
12.
Conclusion
Last Updated: Jun 20, 2024
Medium

Java Operators

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java programming, operators are special symbols that perform specific operations on one or more operands. Operators are essential tools that allow you to manipulate data, perform calculations, & make comparisons in your code. Understanding how to use operators effectively is a fundamental but very important skill for any Java developer. 

Java Operators

In this article, we will learn about the different types of operators available in Java, which include arithmetic, unary, assignment, relational, logical, ternary, bitwise, & shift operators. 

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numeric values. Java provides five basic arithmetic operators:

Addition (+)

Adds two operands together.

Example

int a = 10;
int b = 5;
int sum = a + b; // sum = 15

Subtraction (-)

Subtracts the second operand from the first operand.

Example

int a = 10;
int b = 5;
int difference = a - b; // difference = 5

Multiplication (*)

Multiplies two operands together.

Example

int a = 10;
int b = 5;
int product = a * b; // product = 50

Division (/)

Divides the first operand by the second operand.

Example

int a = 10;
int b = 5;
int quotient = a / b; // quotient = 2

Modulus (%)

Returns the remainder after dividing the first operand by the second operand.

Example

int a = 10;
int b = 3;
int remainder = a % b; // remainder = 1


Note: Arithmetic operators follow the standard order of operations, with multiplication & division having higher precedence than addition & subtraction. You can use parentheses to specify the desired order of operations.

Unary Operators

Unary operators are operators that work on a single operand. Java provides several unary operators:

Increment (++)

Increases the value of the operand by 1.

Example

int a = 5;
a++; // a = 6

Decrement (--)

Decreases the value of the operand by 1.

Example

int a = 5;
a--; // a = 4

Unary plus (+)

Indicates a positive value (has no effect on the operand).

Example

int a = +5; // a = 5

Unary minus (-)

Negates the value of the operand.

Example

int a = 5;
int b = -a; // b = -5

Logical NOT (!)

Inverts the boolean value of the operand.

Example

boolean isTrue = true;
boolean isFalse = !isTrue; // isFalse = false


Note: Unary operators are applied to a single operand & can be used to perform simple operations like incrementing, decrementing, or negating a value.

Assignment Operator

The assignment operator (=) is used to assign a value to a variable. It takes the value on the right side of the operator & assigns it to the variable on the left side.

Example

int age = 25;


In this example, the value 25 is assigned to the variable age using the assignment operator.

Java also provides compound assignment operators that combine an arithmetic operation with an assignment. These operators perform the specified operation on the variable & then assign the result back to the variable.

Compound assignment operators include:

Addition assignment (+=)

Example

int a = 5;
a += 3; // a = 8 (equivalent to a = a + 3)

Subtraction assignment (-=)

Example

int a = 10;
a -= 4; // a = 6 (equivalent to a = a - 4)

Multiplication assignment (*=)

Example

int a = 4;
a *= 2; // a = 8 (equivalent to a = a * 2)

Division assignment (/=)

Example

int a = 10;
a /= 2; // a = 5 (equivalent to a = a / 2)

Modulus assignment (%=)

Example

int a = 10;
a %= 3; // a = 1 (equivalent to a = a % 3)


Note: Assignment operators are essential for storing & updating values in variables throughout your Java programs.

Relational Operators

Relational operators are used to compare two values & determine the relationship between them. They return a boolean value (true or false) based on the comparison result.

Java provides the following relational operators:

Equal to (==)

Checks if two operands are equal.

Example

int a = 5;
int b = 5;
boolean isEqual = (a == b); // isEqual = true

Not equal to (!=)

Checks if two operands are not equal.

Example

int a = 5;
int b = 7;
boolean isNotEqual = (a != b); // isNotEqual = true

Greater than (>)

Checks if the first operand is greater than the second operand.

Example

int a = 10;
int b = 5;
boolean isGreater = (a > b); // isGreater = true

Less than (<)

Checks if the first operand is less than the second operand.

Example

int a = 3;
int b = 7;
boolean isLess = (a < b); // isLess = true

Greater than or equal to (>=)

Checks if the first operand is greater than or equal to the second operand.

Example

int a = 5;
int b = 5;
boolean isGreaterOrEqual = (a >= b); // isGreaterOrEqual = true

Less than or equal to (<=)

Checks if the first operand is less than or equal to the second operand.

Example

int a = 4;
int b = 4;
boolean isLessOrEqual = (a <= b); // isLessOrEqual = true


Note: Relational operators are commonly used in conditional statements & loops to make decisions based on comparisons between values.

Logical Operators

Logical operators are used to combine or negate boolean expressions. They operate on boolean values (true or false) & return a boolean result.

Java provides three logical operators:

Logical AND (&&)

Returns true if both operands are true.

Example

boolean isRaining = true;
boolean isWindy = true;
boolean stayIndoors = isRaining && isWindy; // stayIndoors = true

Logical OR (||)

Returns true if at least one of the operands is true.

Example

boolean isHungry = true;
boolean isThirsty = false;
boolean eatOrDrink = isHungry || isThirsty; // eatOrDrink = true

Logical NOT (!)

Negates the boolean value of the operand.

Example

boolean isLightOn = true;
boolean isDark = !isLightOn; // isDark = false


Logical operators are often used in combination with relational operators to create more complex conditions.

Example

int age = 25;
boolean isStudent = true;
boolean isEligible = (age >= 18) && isStudent; // isEligible = true


In this example, the logical AND operator (&&) is used to check if both conditions (age >= 18 & isStudent) are true.

Note: Logical operators are essential for creating conditional statements & making decisions based on multiple conditions in your Java programs.

Ternary Operator

The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement. It is the only operator in Java that takes three operands.

The syntax of the ternary operator is:

condition ? expression1 : expression2


If the condition evaluates to true, expression1 is evaluated & returned. If the condition evaluates to false, expression2 is evaluated & returned.

Example

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); 


Output:

Adult


In this example, the ternary operator checks if age is greater than or equal to 18. If the condition is true, the string "Adult" is assigned to the status variable. If the condition is false, the string "Minor" is assigned to the status variable.

The ternary operator is useful for simple conditional assignments & can make your code more concise & readable.

However, it's important to use the ternary operator judiciously. If the expressions or conditions become too complex, it's often better to use a traditional if-else statement for clarity & maintainability.

Example

int number = 7;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result); 


Output: 

Odd


In this example, the ternary operator is used to determine if a number is even or odd based on the remainder when divided by 2.

Bitwise Operators

Bitwise operators perform operations on individual bits of integer values. They manipulate the binary representation of numbers.

Java provides the following bitwise operators:

Bitwise AND (&)

Performs a bitwise AND operation on each corresponding bit of the operands.

Example

int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011
int result = a & b;  // Binary: 0001, Decimal: 1

Bitwise OR (|)

Performs a bitwise OR operation on each corresponding bit of the operands.

Example

int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011
int result = a | b;  // Binary: 0111, Decimal: 7

Bitwise XOR (^)

Performs a bitwise XOR (exclusive OR) operation on each corresponding bit of the operands.

Example

int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011
int result = a ^ b;  // Binary: 0110, Decimal: 6

Bitwise complement (~)

Inverts all the bits of the operand.

Example

int a = 5;  // Binary: 0101
int result = ~a;  // Binary: 1010, Decimal: -6


Bitwise operators are often used for low-level operations, such as manipulating flags, masks, or performing bit-level optimizations.

Example:

int flags = 0b0110;  // Binary: 0110
int mask = 0b0100;   // Binary: 0100


// Check if a specific flag is set

boolean isSet = (flags & mask) != 0;  // isSet = true


// Set a specific flag

flags = flags | mask;  // Binary: 0110


// Clear a specific flag

flags = flags & ~mask;  // Binary: 0010


In this example, bitwise operators are used to perform operations on individual bits of the flags variable, such as checking if a specific flag is set, setting a flag, or clearing a flag.

Note: Bitwise operators can be challenging to understand initially, but they provide powerful capabilities for working with bits & optimizing certain operations.

Shift Operators

Shift operators are used to shift the bits of a number left or right by a specified number of positions. They are useful for performing quick multiplication or division by powers of two.

Java provides three shift operators:

Left shift (<<)

Shifts the bits of the first operand to the left by the number of positions specified by the second operand.

Example

int a = 5;  // Binary: 0101
int result = a << 2;  // Binary: 010100, Decimal: 20


In this example, the left shift operator (<<) shifts the bits of a to the left by 2 positions, effectively multiplying a by 2^2 (4).

Signed right shift (>>)

Shifts the bits of the first operand to the right by the number of positions specified by the second operand, preserving the sign bit.

Example

int a = -10;  // Binary: 11111111111111111111111111110110
int result = a >> 2;  // Binary: 11111111111111111111111111111101, Decimal: -3


In this example, the signed right shift operator (>>) shifts the bits of a to the right by 2 positions, effectively dividing a by 2^2 (4) while preserving the sign.

Unsigned right shift (>>>)

Shifts the bits of the first operand to the right by the number of positions specified by the second operand, filling the leftmost positions with zeros.

Example

int a = -10;  // Binary: 11111111111111111111111111110110
int result = a >>> 2;  // Binary: 00111111111111111111111111111101, Decimal: 1073741821


In this example, the unsigned right shift operator (>>>) shifts the bits of a to the right by 2 positions, filling the leftmost positions with zeros, resulting in a positive value.

Shift operators are commonly used for efficient multiplication or division by powers of two, as well as for manipulating bits in low-level programming.

Note: It's important to note that the second operand of the shift operators should be non-negative and less than 32 for int values (or less than 64 for long values) to avoid undefined behavior.

Frequently Asked Questions

What is the difference between the logical AND (&&) and the bitwise AND (&) operator?

The logical AND (&&) operator evaluates the boolean expressions and returns a boolean result, while the bitwise AND (&) operator performs a bitwise operation on the individual bits of the operands.

Can the ternary operator be nested?

Yes, the ternary operator can be nested, meaning you can use another ternary operator as the expression for the true or false condition. However, nesting ternary operators can reduce code readability, so it should be used sparingly.

What happens if you try to divide an integer by zero using the division operator?

If you try to divide an integer by zero using the division operator, it will throw an ArithmeticException at runtime. It's important to handle division by zero cases appropriately in your code to avoid exceptions.

Conclusion

In this article, we saw various types of operators available in Java. We learned about arithmetic operators for performing mathematical calculations, unary operators for working with a single operand, and the assignment operator for assigning values to variables. We also covered relational operators for comparing values, logical operators for combining boolean expressions, and the ternary operator for concise conditional statements. Additionally, we looked into bitwise operators for manipulating individual bits and shift operators for efficient bit shifting. 

You can refer to our guided paths on Code 360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass