In Java, operators are symbols that perform specific operations on one or more operands (variables, constants, or literals) and produce a result. Expressions, on the other hand, are combinations of operators, operands, and method invocations that evaluate to a single value.
Here are some commonly used operators in Java:
- Arithmetic Operators:
- Addition (+): Adds two operands.
- Subtraction (-): Subtracts the second operand from the first.
- Multiplication (*): Multiplies two operands.
- Division (/): Divides the first operand by the second.
- Modulus (%): Returns the remainder of the division.
- Increment (++) and Decrement (–): Increases or decreases the value of an operand by 1.
- Relational Operators:
- Equal to (==): Checks if two operands are equal.
- Not equal to (!=): Checks if two operands are not equal.
- Greater than (>): Checks if the first operand is greater than the second.
- Less than (<): Checks if the first operand is less than the second.
- Greater than or equal to (>=): Checks if the first operand is greater than or equal to the second.
- Less than or equal to (<=): Checks if the first operand is less than or equal to the second.
- Logical Operators:
- Logical AND (&&): Returns true if both operands are true.
- Logical OR (||): Returns true if either of the operands is true.
- Logical NOT (!): Reverses the logical state of the operand.
- Assignment Operators:
- Simple Assignment (=): Assigns a value to a variable.
- Compound Assignment (+=, -=, *=, /=): Performs an operation and assigns the result to the variable.
- Bitwise Operators:
- Bitwise AND (&): Performs a bitwise AND operation.
- Bitwise OR (|): Performs a bitwise OR operation.
- Bitwise XOR (^): Performs a bitwise exclusive OR operation.
- Bitwise complement (~): Inverts the bits of the operand.
- Left shift (<<) and Right shift (>>): Shifts the bits of the operand to the left or right.
These are just a few examples of operators in Java. There are additional operators such as the ternary operator (?:), instanceof operator, bitwise shift operators (<<, >>>, <<<), etc.
Expressions are built using operators and operands. An expression can involve arithmetic calculations, logical comparisons, method invocations, and variable assignments. For example:
int x = 5; int y = 10; int sum = x + y; // Arithmetic expression boolean isTrue = x > y; // Relational expression boolean result = (x > 0) && (y < 20); // Logical expression
In the examples above, the expressions x + y
, x > y
, and (x > 0) && (y < 20)
evaluate to a single value.