Operators in Java are special symbols or keywords used to perform operations on variables and values. They play a crucial role in manipulating data and controlling program flow. Java provides a wide range of operators grouped into several categories based on functionality.
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical tasks such as addition, subtraction, multiplication, division, etc.
-
+
is used to perform addition
int x = 5, y = 10;
int sum = x + y; // sum = 15
-
-
is used for subtraction
int x = 10, y = 5;
int difference = x - y; // difference = 5
-
*
for multiplication
int x = 5, y = 4;
int product = x * y; // product = 20
-
/
for division
int x = 20, y = 4;
int quotient = x / y; // quotient = 5
-
%
is used to find the division remainder
int x = 10, y = 3;
int remainder = x % y; // remainder = 1
-
++
or increment operator increases the value of a variable by 1.
int x = 5;
x++; // x = 6
-
--
or decrement operator Decreases the value of a variable by 1.
int x = 5;
x--; // x = 4
Comparison operators
Comparison operators are used to compare two values (or variables). The return value of a comparison is either true
or false
.
-
==
or Equal to: Checks if two values are equal.
int x = 5, y = 5;
boolean isEqual = (x == y); // isEqual = true
-
!=
or Not equal: Checks if two values are not equal.
int x = 5, y = 10;
boolean isNotEqual = (x != y); // isNotEqual = true
-
>
or Greater than: Checks if one value is greater than another.
int x = 10, y = 5;
boolean isGreaterThan = (x > y); // isGreaterThan = true
-
<
orless than
: Checks if one value is less than another.
int x = 5, y = 10;
boolean isLessThan = (x < y); // isLessThan = true
-
>=
( Greater than or equal to ): Checks if one value is greater than or equal to another.
int x = 10, y = 10;
boolean isGreaterThanOrEqualTo = (x >= y); // isGreaterThanOrEqualTo = true
-
<=
( Less than or equal to ): Checks if one value is less than or equal to another.
int x = 5, y = 10;
boolean isLessThanOrEqualTo = (x <= y); // isLessThanOrEqualTo = true
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Example | Same As |
---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator | Name | Description | Example |
---|---|---|---|
&& |
Logical and | Returns true if both statements are true. | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true. |
x < 5 || x < 4
|
! |
Logical not | Reverses the result, returns false if the result is true. | !(x < 5 && x < 10) |
Conclusion
Operators are the building blocks for manipulating data and implementing logic. Practice using different operators in real-world scenarios to strengthen your command over them.
Top comments (0)