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 8Subtraction -
int difference = 10 - 4; // difference is now 6Multiplication *
int product = 6 * 7; // product is now 42Division /
int quotient = 20 / 4; // quotient is now 5Modulus %
int remainder = 17 % 3; // remainder is now 2Comparison Operators
Comparison operators are used to compare values.
Equal to ==
boolean isEqual = (5 == 5); // isEqual is trueNot equal to !=
boolean isNotEqual = (5 != 3); // isNotEqual is trueGreater than >
boolean isGreater = (10 > 7); // isGreater is trueLess than <
boolean isLess = (3 < 9); // isLess is trueGreater than or equal to >=
boolean isGreaterOrEqual = (8 >= 8); // isGreaterOrEqual is trueLess than or equal to <=
boolean isLessOrEqual = (6 <= 4); // isLessOrEqual is falseLogical Operators
Logical operators are used to perform logical operations.
Logical AND &&
boolean andResult = (true && false); // andResult is falseLogical OR ||
boolean orResult = (true || false); // orResult is trueLogical NOT !
boolean notResult = !true; // notResult is falseAssignment Operators
Assignment operators are used to assign values to variables.
Assignment =
int num = 42; // num is assigned the value 42Addition Assignment +=
int total = 10;
total += 5; // total is now 15Subtraction Assignment -=
int value = 20;
value -= 8; // value is now 12Multiplication Assignment *=
int quantity = 4;
quantity *= 3; // quantity is now 12Division Assignment /=
int amount = 30;
amount /= 2; // amount is now 15Bitwise Operators
Bitwise operators are used for manipulating individual bits of data.
Bitwise AND &
int result = 5 & 3; // result is 1Bitwise OR |
int result = 5 | 3; // result is 7Bitwise XOR ^
int result = 5 ^ 3; // result is 6Bitwise NOT ~
int result = ~5; // result is -6These 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.