Java tutorials > Core Java Fundamentals > Basics and Syntax > What are the different types of operators in Java?
What are the different types of operators in Java?
In Java, operators are special symbols that perform operations on variables and values. Understanding different types of operators is crucial for writing effective and efficient Java code. This tutorial provides a comprehensive overview of the various operator types available in Java.
Introduction to Operators in Java
Operators in Java are symbols that tell the compiler to perform specific mathematical or logical manipulations. Java provides a rich set of operators that can be broadly classified into the following categories:
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. They include: Example: The code snippet demonstrates the use of each arithmetic operator with integer variables.
+
(Addition): Adds two operands.-
(Subtraction): Subtracts the second operand from the first.*
(Multiplication): Multiplies two operands./
(Division): Divides the first operand by the second. If both operands are integers, the result is an integer (truncated).%
(Modulus): Returns the remainder of a division.
int a = 10;
int b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus (Remainder)
Assignment Operators
Assignment operators are used to assign values to variables. The most common assignment operator is Example: The code shows how to use various assignment operators to modify the value of a variable.=
. Other assignment operators combine the assignment with an arithmetic operation:
=
(Simple Assignment): Assigns the value of the right operand to the left operand.+=
(Add and Assign): Adds the right operand to the left operand and assigns the result to the left operand.-=
(Subtract and Assign): Subtracts the right operand from the left operand and assigns the result to the left operand.*=
(Multiply and Assign): Multiplies the left operand by the right operand and assigns the result to the left operand./=
(Divide and Assign): Divides the left operand by the right operand and assigns the result to the left operand.%=
(Modulus and Assign): Calculates the modulus of the left operand by the right operand and assigns the result to the left operand.
int x = 10;
x += 5; // Equivalent to x = x + 5;
System.out.println(x); // Output: 15
x -= 3; // Equivalent to x = x - 3;
System.out.println(x); // Output: 12
x *= 2; // Equivalent to x = x * 2;
System.out.println(x); // Output: 24
x /= 4; // Equivalent to x = x / 4;
System.out.println(x); // Output: 6
x %= 5; // Equivalent to x = x % 5;
System.out.println(x); // Output: 1
Comparison (Relational) Operators
Comparison operators are used to compare two values and return a boolean result ( Example: This code demonstrates how to compare two integer values using comparison operators and print the results.true
or false
). They include:
==
(Equal to): Checks if two operands are equal.!=
(Not equal to): Checks if two operands are not equal.>
(Greater than): Checks if the left operand is greater than the right operand.<
(Less than): Checks if the left operand is less than the right operand.>=
(Greater than or equal to): Checks if the left operand is greater than or equal to the right operand.<=
(Less than or equal to): Checks if the left operand is less than or equal to the right operand.
int a = 10;
int b = 5;
boolean isEqual = (a == b); // Equal to
boolean isNotEqual = (a != b); // Not equal to
boolean isGreaterThan = (a > b); // Greater than
boolean isLessThan = (a < b); // Less than
boolean isGreaterThanOrEqual = (a >= b); // Greater than or equal to
boolean isLessThanOrEqual = (a <= b); // Less than or equal to
System.out.println("Is Equal: " + isEqual); // Output: Is Equal: false
System.out.println("Is Not Equal: " + isNotEqual); // Output: Is Not Equal: true
System.out.println("Is Greater Than: " + isGreaterThan); // Output: Is Greater Than: true
System.out.println("Is Less Than: " + isLessThan); // Output: Is Less Than: false
System.out.println("Is Greater Than or Equal: " + isGreaterThanOrEqual); // Output: Is Greater Than or Equal: true
System.out.println("Is Less Than or Equal: " + isLessThanOrEqual); // Output: Is Less Than or Equal: false
Logical Operators
Logical operators are used to perform logical operations on boolean expressions. They include: Example: The code shows how to combine boolean values using logical operators.
&&
(Logical AND): Returns true
if both operands are true
, otherwise returns false
.||
(Logical OR): Returns true
if either of the operands is true
, otherwise returns false
.!
(Logical NOT): Returns the inverse of the operand. If the operand is true
, it returns false
, and vice versa.
boolean x = true;
boolean y = false;
boolean andResult = x && y; // Logical AND
boolean orResult = x || y; // Logical OR
boolean notResult = !x; // Logical NOT
System.out.println("AND: " + andResult); // Output: AND: false
System.out.println("OR: " + orResult); // Output: OR: true
System.out.println("NOT: " + notResult); // Output: NOT: false
Bitwise Operators
Bitwise operators perform operations on individual bits of integer values. They include: Example: This code demonstrates bitwise operations on integers.
&
(Bitwise AND): Performs a bitwise AND operation.|
(Bitwise OR): Performs a bitwise OR operation.^
(Bitwise XOR): Performs a bitwise XOR (exclusive OR) operation.~
(Bitwise NOT): Inverts all the bits of an operand.<<
(Left Shift): Shifts the bits of the left operand to the left by the number of positions specified by the right operand.>>
(Right Shift): Shifts the bits of the left operand to the right by the number of positions specified by the right operand. Preserves the sign bit.>>>
(Unsigned Right Shift): Shifts the bits of the left operand to the right by the number of positions specified by the right operand. Fills the leftmost bits with zeros.
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int bitwiseAnd = a & b; // 0001 (1 in decimal)
int bitwiseOr = a | b; // 0111 (7 in decimal)
int bitwiseXor = a ^ b; // 0110 (6 in decimal)
int bitwiseNotA = ~a; // Inverts all bits (results depend on the number of bits in int)
int leftShift = a << 2; // 10100 (20 in decimal) - shifts bits to the left
int rightShift = a >> 1; // 0010 (2 in decimal) - shifts bits to the right
int unsignedRightShift = a >>> 1; // 0010 (2 in decimal) - unsigned right shift
System.out.println("Bitwise AND: " + bitwiseAnd);
System.out.println("Bitwise OR: " + bitwiseOr);
System.out.println("Bitwise XOR: " + bitwiseXor);
System.out.println("Bitwise NOT A: " + bitwiseNotA);
System.out.println("Left Shift: " + leftShift);
System.out.println("Right Shift: " + rightShift);
System.out.println("Unsigned Right Shift: " + unsignedRightShift);
Conditional (Ternary) Operator
The conditional operator (also known as the ternary operator) is a shorthand way of writing an If the Example: The code checks if a person is eligible to vote based on their age using the ternary operator.if-else
statement. It has the following syntax:condition ? expression1 : expression2
condition
is true
, expression1
is evaluated and returned. If the condition
is false
, expression2
is evaluated and returned.
int age = 20;
String message = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(message); // Output: Eligible to vote
Operator Precedence
Operator precedence determines the order in which operators are evaluated in an expression. It's essential to understand precedence to write correct code. For example, multiplication and division have higher precedence than addition and subtraction. To avoid ambiguity, it is often best practice to use parentheses to explicitly define the order of operations. Example:int result = 5 + 3 * 2; // result will be 11 (3 * 2 is evaluated first)
int result = (5 + 3) * 2; // result will be 16 (5 + 3 is evaluated first)
Real-Life Use Case Section
Operators are used extensively in various real-life scenarios:
Best Practices
&&
) and logical OR (||
) operators use short-circuiting. The second operand is not evaluated if the result can be determined from the first operand.
Interview Tip
When discussing operators in an interview, be prepared to explain:
When to use them
Choosing the right operator depends on the specific task at hand. Use:
if-else
statements.
Memory footprint
The memory footprint of operators themselves is negligible. The memory usage is primarily determined by the data types of the operands. For example, operating on int
variables will consume more memory than operating on byte
variables.
Alternatives
For some operations, there might be alternative approaches, but operators are usually the most efficient and concise way to perform basic tasks. For example, instead of using the conditional operator, you can use a full if-else
statement, but the conditional operator is often more readable for simple conditions.
Pros and Cons
FAQ
-
What happens if I divide an integer by zero?
Dividing an integer by zero results in anArithmeticException
at runtime. -
What is short-circuiting in logical operators?
Short-circuiting means that the second operand of a logical AND (&&
) or logical OR (||
) operator is not evaluated if the result can be determined from the first operand. For example, in(false && someMethod())
,someMethod()
will not be executed because the result will always befalse
. -
How does the ternary operator work?
The ternary operator is a shorthand for an if-else statement. It takes the formcondition ? expression1 : expression2
. If thecondition
is true,expression1
is evaluated; otherwise,expression2
is evaluated. -
What's the difference between '==' and '.equals()' in Java?
The '==' operator compares references (memory addresses), while the '.equals()' method compares the contents of objects. For primitive types, '==' compares values directly. For objects, you should usually use '.equals()' to compare content. Always override the `.equals()` method in your custom classes to define what equality means for your objects.