In Java, operators are symbols that perform operations on operands. Operands can be variables, constants, or expressions. Understanding Java operators and their usage is fundamental to programming in the language. In this article, we’ll explore various types of Java operators with examples.
Arithmetic Operators
Arithmetic operators are used to performing mathematical calculations.
Addition +
int sum = 5 + 3; // sum is now 8
Subtraction -
int difference = 10 - 4; // difference is now 6
Multiplication *
int product = 6 * 7; // product is now 42
Division /
int quotient = 20 / 4; // quotient is now 5
Modulus %
int remainder = 17 % 3; // remainder is now 2
Comparison Operators
Comparison operators are used to compare values.
Equal to ==
boolean isEqual = (5 == 5); // isEqual is true
Not equal to !=
boolean isNotEqual = (5 != 3); // isNotEqual is true
Greater than >
boolean isGreater = (10 > 7); // isGreater is true
Less than <
boolean isLess = (3 < 9); // isLess is true
Greater than or equal to >=
boolean isGreaterOrEqual = (8 >= 8); // isGreaterOrEqual is true
Less than or equal to <=
boolean isLessOrEqual = (6 <= 4); // isLessOrEqual is false
Logical Operators
Logical operators are used to perform logical operations.
Logical AND &&
boolean andResult = (true && false); // andResult is false
Logical OR ||
boolean orResult = (true || false); // orResult is true
Logical NOT !
boolean notResult = !true; // notResult is false
Assignment Operators
Assignment operators are used to assign values to variables.
Assignment =
int num = 42; // num is assigned the value 42
Addition Assignment +=
int total = 10;
total += 5; // total is now 15
Subtraction Assignment -=
int value = 20;
value -= 8; // value is now 12
Multiplication Assignment *=
int quantity = 4;
quantity *= 3; // quantity is now 12
Division Assignment /=
int amount = 30;
amount /= 2; // amount is now 15
Bitwise Operators
Bitwise operators are used for manipulating individual bits of data.
Bitwise AND &
int result = 5 & 3; // result is 1
Bitwise OR |
int result = 5 | 3; // result is 7
Bitwise XOR ^
int result = 5 ^ 3; // result is 6
Bitwise NOT ~
int result = ~5; // result is -6
These are just a few examples of the operators available in Java. Operators are a fundamental part of programming and are used extensively to perform a wide range of tasks. Understanding how and when to use these operators is essential for writing efficient and effective Java code.