Curriculum
In Java, operators are symbols used to perform specific operations on one or more operands. Java supports a wide range of operators, including arithmetic, relational, logical, bitwise, and assignment operators. Here are some examples of the most common operators in Java:
Arithmetic operators are used to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and modulo. Here are some examples:
int a = 10; int b = 3; int sum = a + b; // 13 int difference = a - b; // 7 int product = a * b; // 30 int quotient = a / b; // 3 int remainder = a % b; // 1
Relational operators are used to compare two values and return a boolean value (true or false). Here are some examples:
int a = 10; int b = 3; boolean isEqual = (a == b); // false boolean isNotEqual = (a != b); // true boolean isGreaterThan = (a > b); // true boolean isGreaterThanOrEqual = (a >= b); // true boolean isLessThan = (a < b); // false boolean isLessThanOrEqual = (a <= b); // false
Logical operators are used to combine multiple conditions and return a boolean value (true or false). Here are some examples:
int a = 10; int b = 3; boolean isTrue = (a > b) && (a < 20); // true boolean isFalse = (a < b) || (b > 5); // true boolean isNot = !(a > b); // false
Bitwise operators are used to perform operations on individual bits of a number. Here are some examples:
int a = 60; // 0011 1100 int b = 13; // 0000 1101 int andResult = a & b; // 0000 1100 int orResult = a | b; // 0011 1101 int xorResult = a ^ b; // 0011 0001 int notResult = ~a; // 1100 0011 int leftShiftResult = a << 2; // 1111 0000 int rightShiftResult = a >> 2; // 0000 1111 int unsignedRightShiftResult = a >>> 2; // 0000 1111
Assignment operators are used to assign values to variables. Here are some examples:
int a = 10; a += 5; // a is now 15 a -= 3; // a is now 12 a *= 2; // a is now 24 a /= 4; // a is now 6 a %= 5; // a is now 1
These are just a few examples of the most common operators in Java. It is important to note that each operator has its own set of rules regarding the types of operands it can be used with, so it is important to understand these rules before using operators in your code.
Here are some general rules to keep in mind when using operators in Java:
+
operator can be used to add two int
values, but not an int
and a String
.+
operator can be used with two int
values, but not an int
and a double
.+
operator is left-associative, which means that expressions such as 1 + 2 + 3
are evaluated as (1 + 2) + 3
./
, must not be zero. Otherwise, a runtime exception will occur.<<
, >>
, and >>>
, can result in unexpected behavior if used with negative operands.