Summary: In this tutorial, you will learn about different types of operators in Java with the help of examples.
In Java, an operator is a symbol that performs a specific operation on one or more operands (values or variables).
Operators can be used to perform a wide variety of tasks, such as arithmetic calculations, comparisons, assignments, and logical operations.
Java has a number of different types of operators, including:
Arithmetic operators
These operators are used to perform basic arithmetic operations, such as addition, subtraction, multiplication, and division. The arithmetic operators in Java are:
+: addition-: subtraction*: multiplication/: division%: modulus (remainder of division)++: increment (add 1 to a value)--: decrement (subtract 1 from a value)
int x = 10;
int y = 5;
int sum = x + y; // 15
int product = x * y; // 50
Comparison Operators
These operators are used to compare two values and return a boolean result indicating whether the comparison is true or false. The comparison operators in Java are:
==: equal to!=: not equal to>: greater than<: less than>=: greater than or equal to<=: less than or equal to
Assignment Operators
These operators are used to assign a value to a variable. The assignment operators in Java are:
=: simple assignment (assigns a value to a variable)+=: add and assign (adds a value to a variable and assigns the result to the variable)-=: subtract and assign (subtracts a value from a variable and assigns the result to the variable)*=: multiply and assign (multiplies a variable by a value and assigns the result to the variable)/=: divide and assign (divides a variable by a value and assigns the result to the variable)%=: modulus and assign (calculates the remainder of dividing a variable by a value and assigns the result to the variable)
Here is an example of using assignment operators in Java:
int x = 10;
int y = 5;
x += y; // x is now 15
x -= y; // x is now 10
x *= y; // x is now 50
x /= y; // x is now 10
x %= y; // x is now 0
Logical Operators
These operators are used to perform logical operations, such as AND, OR, and NOT. The logical operators in Java are:
&&: logical AND (returns true if both operands are true, otherwise returns false)||: logical OR (returns true if at least one operand is true, otherwise returns false)!: logical NOT (negates the boolean value of the operand)
boolean a = true;
boolean b = false;
boolean result = a && b; // result is false
result = a || b; // result is true
result = !a; // result is false
Conditional Operators
These operators are used to perform different actions based on a boolean condition. The conditional operator in Java is the if statement.
Here is an example of using a conditional operator in Java:
int x = 10;
if (x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is not positive");
}