In Java, operators are used to perform various operations on variables and values. Here are some of the most commonly used operators in Java:
1. Arithmetic Operators:Arithmetic operators are used to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. The following arithmetic operators are supported in Java:
+: addition
-: subtraction
*: multiplication
/: division
%: modulus (returns the remainder of division)
Here's an example of using arithmetic operators to perform basic arithmetic operations:
int a = 10;
int b = 20;
int sum = a + b; // addition
int diff = b - a; // subtraction
int prod = a * b; // multiplication
int quotient = b / a; // division
int remainder = b % a; // modulus
2. Relational Operators:
Relational operators are used to compare two values or variables. They return a boolean value (true or false) based on whether the comparison is true or false. The following relational operators are supported in Java:
==: equal to
!=: not equal to
<: less than
>: greater than
<=: less than or equal to
>=: greater than or equal to
Here's an example of using relational operators to compare two variables:
int a = 10;
int b = 20;
boolean isEqual = (a == b); // false
boolean isNotEqual = (a != b); // true
boolean isLessThan = (a < b); // true
boolean isGreaterThan = (a > b); // false
boolean isLessThanOrEqual = (a <= b); // true
boolean isGreaterThanOrEqual = (a >= b); // false
3. Logical Operators:
Logical operators are used to combine multiple boolean expressions or values. The following logical operators are supported in Java:
&&: logical AND
||: logical OR
!: logical NOT
Here's an example of using logical operators to combine boolean values:
boolean a = true;
boolean b = false;
boolean c = true;
boolean result = (a && b) || c; // true
boolean negation = !result; // false
4. Assignment Operators:
Assignment operators are used to assign a value to a variable. The following assignment operators are supported in Java:
= : simple assignment
+= : add and assign
-= : subtract and assign
*= : multiply and assign
/= : divide and assign
%= : modulus and assign
Here's an example of using assignment operators to assign values to variables:
int a = 10;
a += 5; // equivalent to a = a + 5
a -= 2; // equivalent to a = a - 2
a *= 3; // equivalent to a = a * 3
a /= 2; // equivalent to a = a / 2
a %= 4; // equivalent to a = a % 4
In summary, Java supports a variety of operators for performing arithmetic, comparison, logical, and assignment operations. Understanding these operators is crucial for developing effective Java programs.