Operators in Java
In Java, operators are special symbols or characters that are used to perform certain operations on one or more operands. Java supports a wide range of operators, including:
- Arithmetic Operators: These operators are used to perform mathematical calculations on numerical values. The arithmetic operators in Java include:
- (addition)
- (subtraction)
- (multiplication) / (division) % (modulus or remainder)
- Assignment Operators: These operators are used to assign values to variables. The assignment operators in Java include:
= (simple assignment) += (addition and assignment) -= (subtraction and assignment) *= (multiplication and assignment) /= (division and assignment) %= (modulus and assignment)
- Comparison Operators: These operators are used to compare two values and return a boolean value (true or false). The comparison operators in Java include:
== (equal to) != (not equal to)
(greater than) < (less than) = (greater than or equal to) <= (less than or equal to)
- Logical Operators: These operators are used to combine two or more boolean expressions and return a boolean value. The logical operators in Java include:
&& (logical AND) || (logical OR) ! (logical NOT)
- Bitwise Operators: These operators are used to perform bitwise operations on two numerical values. The bitwise operators in Java include:
& (bitwise AND) | (bitwise OR) ^ (bitwise XOR) ~ (bitwise NOT) << (left shift)
- Ternary Operator: This operator is used to assign one of two values to a variable depending on a boolean expression. The ternary operator in Java is denoted by the symbol "?:".
Example: int x = (a > b) ? a : b; // assigns the larger of a and b to x.
These are some of the commonly used operators in Java.
Java Operator Precedence
Java operator precedence determines the order in which operators are evaluated in an expression. In Java, operators with higher precedence are evaluated first. If operators have the same precedence, they are evaluated from left to right. Here is a summary of Java operator precedence, from highest to lowest:
| |||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Operators with higher precedence are evaluated before operators with lower precedence. Parentheses can be used to override the default precedence order and specify the order of evaluation. | |||||||||||||||||||||||||||||||||||||||||
Java Unary OperatorIn Java, a unary operator is an operator that operates on a single operand. There are several unary operators in Java:
Unary operators have a higher precedence than binary operators in Java, except for the postfix increment and decrement operators which have the same precedence as other binary operators. |
|||||||||||||||||||||||||||||||||||||||||
0 Comments