All About Java Operators

All About Java Operators

18 mins read1.3K Views 1 Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Oct 13, 2024 21:31 IST

Have you ever wondered how Java performs calculations, makes decisions, or manipulates data so efficiently? This is where Java operators come into play. Operators in Java are special symbols that perform operations on variables and values, allowing you to execute everything from basic arithmetic to complex logical comparisons and bit manipulations. Let's understand more!

Operators in Java are special symbols that perform specific operations on one, two, or three operands and then return a result. They are essential for performing different types of operations on variables and values within the program.

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
6 weeks
15 K
3 months
2.05 K
3 months
– / –
170 hours
5.4 K
1 month
– / –
6 months
– / –
2 months
17 K
3 months
5.5 K
1 month

Check out Java courses here!

Why Do We Need Java Operators

  • Operators allow the execution of arithmetic calculations essential for any mathematical operations in your program.
  •  They enable decision-making in the code through comparison and logical operators, directing the execution flow based on conditions.
  •  They are used to manipulate data at both bit and byte levels, allowing for efficient data processing.
  • Operators like the assignment and unary operators simplify code by reducing complexity and increasing readability.
  • Operators, especially bitwise and shift operators, can perform operations faster than their functional equivalents, enhancing performance.

Types of Java Operators

 

 

Let's elaborate on each type in detail!

1. Arithmetic Operators

The arithmetic operator in Java performs mathematical operations between numerical values. These operators are fundamental tools in Java for manipulating numbers and implementing calculations within the program. 

Operator

Name

Description

Example

+

Addition

Adds two values together.

5 + 3 results in 8

-

Subtraction

Subtracts the second value from the first.

5 - 3 results in 2

*

Multiplication

Multiplies two values.

5 * 3 results in 15

/

Division

Divides the first value by the second, giving the quotient.

6 / 3 results in 2

%

Modulus

Computes the remainder of the division of the first value by the second.

7 % 3 results in 1

++

Increment

Increases the value by one. It can be used as a prefix or suffix.

If a = 5, then ++a or a++ results in 6

--

Decrement

Decreases the value by one. It can be used as a prefix or suffix.

If a = 5, then --a or a-- results in 4

All About Arithmetic Operators in Java

Example:

Suppose we want to create a simple Java program that demonstrates the use of all the basic arithmetic operators. We'll perform various operations on two integers: a and b. Here are the tasks:

  • Add a and b.
  • Subtract b from a.
  • Multiply a and b.
  • Divide a by b.
  • Find the remainder when a is divided by b.
  • Increment a by 1.
  • Decrement b by 1.

Let's use a = 15 and b = 4 for this example.


 
public class ArithmeticDemo {
public static void main(String[] args) {
int a = 15;
int b = 4;
// Addition
int addition = a + b;
System.out.println("Addition: " + addition);
// Subtraction
int subtraction = a - b;
System.out.println("Subtraction: " + subtraction);
// Multiplication
int multiplication = a * b;
System.out.println("Multiplication: " + multiplication);
// Division
int division = a / b;
System.out.println("Division: " + division);
// Modulus
int modulus = a % b;
System.out.println("Modulus: " + modulus);
// Increment
a++;
System.out.println("Increment: " + a);
// Decrement
b--;
System.out.println("Decrement: " + b);
}
}
Copy code

Output

Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
Increment: 16
Decrement: 3

2. Relational (Comparison) Operators

Relational (or comparison) operators in Java are used to compare two values or expressions, resulting in a boolean value (true or false). These operators are crucial for controlling the flow of execution in the program, such as in conditional statements (if, else) and loops (while, for).

Operator

Name

Description

Example

==

Equal to

Checks if two values are equal.

5 == 5 results in true

!=

Not equal to

Checks if two values are not equal.

5 != 4 results in true

>

Greater than

Checks if the left value is greater than the right value.

5 > 3 results in true

<

Less than

Checks if the left value is less than the right value.

3 < 5 results in true

>=

Greater than or equal to

Checks if the left value is greater than or equal to the right value.

5 >= 5 results in true

<=

Less than or equal to

Checks if the left value is less than or equal to the right value.

3 <= 5 results in true

Relational Operators in Java | About, Types and Examples

Example:

Create a Java program that demonstrates the use of all the relational (comparison) operators. We'll use a series of comparisons between two integer variables, x and y, to illustrate how each operator works and when they return true or false. For this example, let's use x = 10 and y = 20.


 
public class ComparisonDemo {
public static void main(String[] args) {
int x = 10;
int y = 20;
// Equal to
boolean isEqual = x == y;
System.out.println("Is Equal: " + isEqual); // Expected: false
// Not equal to
boolean isNotEqual = x != y;
System.out.println("Is Not Equal: " + isNotEqual); // Expected: true
// Greater than
boolean isGreaterThan = x > y;
System.out.println("Is Greater Than: " + isGreaterThan); // Expected: false
// Less than
boolean isLessThan = x < y;
System.out.println("Is Less Than: " + isLessThan); // Expected: true
// Greater than or equal to
boolean isGreaterThanOrEqual = x >= y;
System.out.println("Is Greater Than or Equal: " + isGreaterThanOrEqual); // Expected: false
// Less than or equal to
boolean isLessThanOrEqual = x <= y;
System.out.println("Is Less Than or Equal: " + isLessThanOrEqual); // Expected: true
}
}
Copy code

Output

Is Equal: false
Is Not Equal: true
Is Greater Than: false
Is Less Than: true
Is Greater Than or Equal: false
Is Less Than or Equal: true

3. Logical Operators

Logical operators in Java are used to combine multiple boolean expressions into a single expression, which also results in a boolean value (true or false). These operators are essential in controlling the execution flow through complex conditions in programming constructs like if statements, loops, and switch cases.

Operator

Name

Description

&&

Logical AND

Returns true only if both operands are true.

||

Logical OR

Returns true if at least one of the operands is true. If both operands are false, the result is false.

!

Logical NOT

Inverts the truth value of the operand.

Let's Learn Logical Operators in Java

Example:

Create a Java program that demonstrates the use of all the logical operators (&&, ||, !). The program will check various conditions related to a person's eligibility to participate in different activities based on their age and weather conditions.


 
public class LogicalOperatorsExample {
public static void main(String[] args) {
int age = 20;
boolean hasTicket = true;
boolean isRaining = false;
// Logical AND (&&)
// Check if the person is over 18 and has a ticket
if (age > 18 && hasTicket) {
System.out.println("Eligible to enter concert.");
} else {
System.out.println("Not eligible to enter concert.");
}
// Logical OR (||)
// Check if the person is either under 18 or it is raining
if (age < 18 || isRaining) {
System.out.println("Eligible for free entry to the museum.");
} else {
System.out.println("Regular entry fees apply for the museum.");
}
// Logical NOT (!)
// Check if it is not raining
if (!isRaining) {
System.out.println("Great weather for a walk!");
} else {
System.out.println("Stay indoors, it's raining.");
}
}
}
Copy code

Output

Eligible to enter concert.
Regular entry fees apply for the museum.
Great weather for a walk!

4. Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits of integer numbers (both int and long types). These operators are particularly useful in low-level programming where data manipulation at the binary level is required, such as graphics, device drivers, and encryption. 

Operator

Name

Description

Example

&

Bitwise AND

Compares each bit of two numbers. Bit is set if both bits are 1.

a & b

^

Bitwise XOR

Compares each bit of two numbers. Bit is set if only one of the bits is 1.

a ^ b

~

Bitwise NOT

Inverts all the bits of a number.

~a

Mastering Bitwise Operator in Java

Example:

Create a Java program that demonstrates the use of all the primary bitwise operators. We'll use a series of operations on two integer variables, a and b, to illustrate how each operator manipulates bits directly.


 
public class BitwiseOperatorsExample {
public static void main(String[] args) {
int a = 12; // binary representation: 1100
int b = 5; // binary representation: 0101
// Bitwise AND
int andResult = a & b; // Both bits must be 1
System.out.println("Bitwise AND: " + andResult);
// Bitwise OR
int orResult = a | b; // At least one bit must be 1
System.out.println("Bitwise OR: " + orResult);
// Bitwise XOR
int xorResult = a ^ b; // Bits must be different
System.out.println("Bitwise XOR: " + xorResult);
// Bitwise NOT
int notResult = ~a; // Invert all bits
System.out.println("Bitwise NOT: " + notResult);
// Shift Left
int shiftLeftResult = a << 2; // Shift bits of 'a' left by 2 positions
System.out.println("Shift Left: " + shiftLeftResult);
// Shift Right
int shiftRightResult = a >> 2; // Shift bits of 'a' right by 2 positions
System.out.println("Shift Right: " + shiftRightResult);
// Unsigned Shift Right
int unsignedShiftRightResult = a >>> 2; // Shift bits of 'a' right by 2 positions, fill with 0
System.out.println("Unsigned Shift Right: " + unsignedShiftRightResult);
}
}
Copy code

Output

Bitwise AND: 4
Bitwise OR: 13
Bitwise XOR: 9
Bitwise NOT: -13
Shift Left: 48
Shift Right: 3
Unsigned Shift Right: 3

5. Assignment Operators

Assignment operators in Java are used to assign values to variables in a more concise way, often while performing some arithmetic or bitwise operation at the same time. These operators reduce the length of the code and can make complex assignment operations more readable and manageable. 

Operator

Name

Description

Example

=

Simple assignment

Assigns the right-hand operand's value to the left-hand operand.

a = b

+=

Add and assign

Adds both operands and assigns the result to the left operand.

a += b (equivalent to a = a + b)

-=

Subtract and assign

Subtracts the right operand from the left operand and assigns the result to the left operand.

a -= b (equivalent to a = a - b)

*=

Multiply and assign

Multiplies both operands and assigns the result to the left operand.

a *= b (equivalent to a = a * b)

/=

Divide and assign

Divides the left operand by the right operand and assigns the result to the left operand.

a /= b (equivalent to a = a / b)

%=

Modulus and assign

Takes modulus using two operands and assigns the result to the left operand.

a %= b (equivalent to a = a % b)

All About Assignment Operator in Java

Example:

Create a Java program that demonstrates the use of all common assignment operators. The program will perform various arithmetic and bitwise operations on several variables to showcase how these operators simplify code and manage the values of variables efficiently.


 
public class AssignmentOperatorsExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Simple assignment
int c = a; // assigns the value of 'a' to 'c'
System.out.println("Simple Assignment: c = " + c);
// Add and assign
a += b; // equivalent to a = a + b
System.out.println("Add and Assign: a = " + a);
// Subtract and assign
a -= b; // equivalent to a = a - b
System.out.println("Subtract and Assign: a = " + a);
// Multiply and assign
a *= b; // equivalent to a = a * b
System.out.println("Multiply and Assign: a = " + a);
// Divide and assign
a /= b; // equivalent to a = a / b
System.out.println("Divide and Assign: a = " + a);
// Modulus and assign
a %= b; // equivalent to a = a % b
System.out.println("Modulus and Assign: a = " + a);
// Bitwise AND and assign
a &= b; // equivalent to a = a & b
System.out.println("Bitwise AND and Assign: a = " + a);
// Bitwise OR and assign
a |= b; // equivalent to a = a | b
System.out.println("Bitwise OR and Assign: a = " + a);
// Bitwise XOR and assign
a ^= b; // equivalent to a = a ^ b
System.out.println("Bitwise XOR and Assign: a = " + a);
// Shift left and assign
c <<= 2; // equivalent to c = c << 2
System.out.println("Shift Left and Assign: c = " + c);
// Shift right and assign
c >>= 2; // equivalent to c = c >> 2
System.out.println("Shift Right and Assign: c = " + c);
// Unsigned shift right and assign
c >>>= 2; // equivalent to c = c >>> 2
System.out.println("Unsigned Shift Right and Assign: c = " + c);
}
}
Copy code

Output

Simple Assignment: c = 10
Add and Assign: a = 15
Subtract and Assign: a = 10
Multiply and Assign: a = 50
Divide and Assign: a = 10
Modulus and Assign: a = 0
Bitwise AND and Assign: a = 0
Bitwise OR and Assign: a = 5
Bitwise XOR and Assign: a = 0
Shift Left and Assign: c = 40
Shift Right and Assign: c = 10
Unsigned Shift Right and Assign: c = 2

6. Unary Operators

Unary operators in Java require only one operand to perform various operations, such as incrementing/decrementing a value, negating an expression, or inverting the value of a boolean.

Operator

Name

Description

Example

+

Unary plus

Indicates the positive value of a variable.

+a

-

Unary minus

Negates the value of a variable.

-a

++

Increment

Increases an integer's value by one.

a++ or ++a

--

Decrement

Decreases an integer's value by one.

a-- or --a

!

Logical NOT

Inverts the boolean value of a condition.

!true is false

Understanding Unary Operator in Java

Example:

Create a Java program that demonstrates the use of all common unary operators. The program will perform operations such as incrementing, decrementing, negating a number, and inverting a boolean value, showing how these operators manipulate individual operands.


 
public class UnaryOperatorsExample {
public static void main(String[] args) {
int a = 10;
boolean flag = false;
// Unary plus
int positive = +a; // Indicates positive value explicitly
System.out.println("Unary Plus: " + positive); // Outputs 10
// Unary minus
int negative = -a; // Negates the value
System.out.println("Unary Minus: " + negative); // Outputs -10
// Increment operator
int preIncrement = ++a; // Increments 'a' by 1 before using it in the expression
System.out.println("Pre-Increment: " + preIncrement); // Outputs 11
int postIncrement = a++; // Increments 'a' by 1 after using it in the expression
System.out.println("Post-Increment: " + postIncrement); // Outputs 11, but 'a' is now 12
// Decrement operator
int preDecrement = --a; // Decrements 'a' by 1 before using it in the expression
System.out.println("Pre-Decrement: " + preDecrement); // Outputs 11
int postDecrement = a--; // Decrements 'a' by 1 after using it in the expression
System.out.println("Post-Decrement: " + postDecrement); // Outputs 11, but 'a' is now 10
// Logical NOT
boolean notFlag = !flag; // Inverts the boolean value of 'flag'
System.out.println("Logical NOT: " + notFlag); // Outputs true
}
}
Copy code

Output

Unary Plus: 10
Unary Minus: -10
Pre-Increment: 11
Post-Increment: 11
Pre-Decrement: 11
Post-Decrement: 11
Logical NOT: true

7. Ternary Operator

The ternary operator in Java is the only conditional operator that takes three operands and is a shorthand for the if-else statement.

Syntax:

condition ? expression1 : expression2;

Here's what each part of the ternary operator means:

  • condition: This is a boolean expression that evaluates to either true or false.
  • expression1: This expression is executed if the condition is true.
  • expression2: This expression is executed if the condition is false.

Learning What is Ternary Operator in Java

Example:

Consider a scenario where you need to assign a grade based on a student's score.


 
public class TernaryOperatorGrading {
public static void main(String[] args) {
int score = 85; // Score obtained by the student
String grade; // Variable to hold the grade
// Using ternary operator to assign grade based on the score
grade = (score >= 90) ? "A" :
(score >= 80) ? "B" : "C";
System.out.println("The student's grade is: " + grade);
}
}
Copy code

Output

The student's grade is: B

8. Shift Operators

Shift operators in Java move the bit positions of an integer operand left or right, filling in with zeros or the sign bit.

Operator

Name

Description

Example

<<

Shift left

Shifts the bits of the number to the left and fills 0 on voids left as a result. The leftmost bits are discarded.

a << 2

>>

Shift right

Shifts the bits of the number to the right. Sign bits are used to fill the voids left from the shift.

a >> 2

>>>

Unsigned shift right

Shifts the bits of the number to the right and fills 0 on voids left.

a >>> 2

Understanding Shift Operator in Java

Example:

Create a Java program that demonstrates the use of shift operators to manipulate the bit positions of integer values. The program will perform left shift, right shift, and unsigned right shift operations, showing how these operators affect the binary representation of numbers.


 
public class ShiftOperatorsExample {
public static void main(String[] args) {
int number = 8; // Binary representation: 1000
// Left Shift Operator
int leftShift = number << 2; // Shifts the bits of 'number' 2 places to the left
System.out.println("Left Shift: " + leftShift + " (Binary: " + Integer.toBinaryString(leftShift) + ")");
// Right Shift Operator
int rightShift = number >> 2; // Shifts the bits of 'number' 2 places to the right
System.out.println("Right Shift: " + rightShift + " (Binary: " + Integer.toBinaryString(rightShift) + ")");
// Unsigned Right Shift Operator
int unsignedRightShift = number >>> 2; // Shifts the bits of 'number' 2 places to the right, fills with zero
System.out.println("Unsigned Right Shift: " + unsignedRightShift + " (Binary: " + Integer.toBinaryString(unsignedRightShift) + ")");
// Demonstrate right shift on a negative number
int negativeNumber = -8; // Binary representation will be in two's complement
int negativeRightShift = negativeNumber >> 2; // Shifts the bits of 'negativeNumber' 2 places to the right
System.out.println("Negative Right Shift: " + negativeRightShift + " (Binary: " + Integer.toBinaryString(negativeRightShift) + ")");
}
}
Copy code

Output

Left Shift: 32 (Binary: 100000)
Right Shift: 2 (Binary: 10)
Unsigned Right Shift: 2 (Binary: 10)
Negative Right Shift: -2 (Binary: 11111111111111111111111111111110)

9. Miscellaneous Operators

Some of the miscellaneous operators in Java are given below:

Operator

Name

Description

Example

instanceof

Type check

Checks whether an object is an instance of a specific class or implements an interface.

obj instanceof String

(type)

Cast

Converts a variable to a specified type.

(int) 5.99

Example:

Create a Java program that demonstrates the use of miscellaneous operators in Java, specifically focusing on the instanceof operator for type checking and the cast operator for type conversion. The program will:

  • Determine if an object is an instance of a certain class.
  • Convert a floating-point number to an integer using casting.

 
public class MiscellaneousOperatorsExample {
public static void main(String[] args) {
// Using 'instanceof' to check the type of an object
Object text = "Hello, Java!";
boolean isString = text instanceof String; // Check if 'text' is an instance of String
System.out.println("Is 'text' an instance of String? " + isString);
// Using casting to convert double to int
double pi = 3.14159;
int integerPart = (int) pi; // Cast double to int, truncating the decimal part
System.out.println("Integer part of pi: " + integerPart);
}
}
Copy code

Output

Is 'text' an instance of String? true
Integer part of pi: 3

Thus, these operators in Java provide a wide range of functionalities, from basic arithmetic and logic operations to more complex decision-making and bitwise manipulations, essential for effective programming and execution control.

FAQs

What is an operator in Java?

An operator in Java is a symbol that is used to perform operations on variables and values. Operators can perform functions like arithmetic calculations, logical comparisons, and more.

How many types of operators are there in Java?

Java has several types of operators: Arithmetic, Relational (Comparison), Logical, Bitwise, Assignment, Unary, Ternary (Conditional), and Miscellaneous operators.

What is the difference between the == and equals() method in Java?

The == operator in Java is used for checking if two references point to the same object, whereas the equals() method is used to compare the contents of two objects.

Can you explain the use of the ternary operator in Java?

The ternary operator (?:) is a shorthand for the if-else statement and is used to assign a value based on a condition. It takes three operands: a condition, a value if true, and a value if false.

What does the instanceof operator do?

The instanceof operator checks whether a specific object is an instance of a class, a subclass, or an interface.

What is the purpose of bitwise operators?

Bitwise operators perform operations on the bits of integers. They are used for tasks that involve manipulation and querying of individual bits within an integer’s binary representation.

How do assignment operators work in Java?

Assignment operators are used to assign values to variables. In Java, simple assignment is done using the = operator, and there are also compound assignment operators like +=, -=, which combine an arithmetic operation with assignment.

What is operator precedence in Java?

Operator precedence determines the order in which operators are evaluated in expressions. For example, multiplication and division have a higher precedence than addition and subtraction.

What does the >>> operator do?

The >>> operator is an unsigned right shift operator that shifts the bits of the operand to the right, filling the leftmost bits with zeros regardless of the sign of the initial value.

Can you use logical operators with non-boolean values?

In Java, logical operators like && and || expect boolean operands and cannot be used with non-boolean values directly. However, bitwise operators like & and | can be used with integers to perform similar logical operations on individual bits.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio

Comments

(1)

Sure! Here's a concise paragraph of comments for the blog "All About Java Operators": "Your blog on Java operators is incredibly informative and well-structured. I particularly enjoyed how you covered a wide range of operators, from arithmetic and bitwise to assignment and logical. The examples prov

Reply to John Miachel

57934521

Esha GuptaAssociate Senior Executive

Thank you so much!