Java Operators
Operators are special symbols that tell the Java compiler to perform arithmetic, comparison, logical, or bitwise operations on one or more operands. Java h...
Performing Operations on Data in Java
Operators are special symbols that tell the Java compiler to perform arithmetic, comparison, logical, or bitwise operations on one or more operands. Java has a rich set of operators organized into categories, and understanding operator precedence — which determines the order in which operators are evaluated in an expression — is essential for writing correct calculations.
Arithmetic operators perform mathematical computations: + for addition, - for subtraction, * for multiplication, / for division, and % for modulus (remainder). Integer division truncates toward zero: 7 / 2 evaluates to 3, not 3.5. To get a decimal result, at least one operand must be a floating-point type: 7.0 / 2 evaluates to 3.5. The modulus operator is useful for determining whether a number is even or odd: if (n % 2 == 0) means n is even.
Relational operators compare two values and return a boolean: == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal), <= (less than or equal). Never use == to compare String objects for content equality; == checks whether two references point to the same object, while .equals() checks whether two strings contain the same characters.
Logical operators combine boolean expressions: && (logical AND, short-circuit), || (logical OR, short-circuit), and ! (logical NOT). Short-circuit evaluation means that in a && b, if a is false, b is never evaluated. This behavior is useful and sometimes essential: if (list != null && list.size() > 0) safely avoids a NullPointerException.
Assignment operators combine an operation with assignment: x += 5 is shorthand for x = x + 5. Similarly, -=, *=, /=, and %= work the same way.
The increment (++) and decrement (--) operators add or subtract 1 from a variable. They come in prefix form (++x, --x), which modifies the value before it is used in the expression, and postfix form (x++, x--), which uses the current value first and then modifies it. The expression int y = x++ assigns x's current value to y and then increments x, while int y = ++x increments x first and then assigns the new value to y.
The ternary operator is a compact conditional: condition ? valueIfTrue : valueIfFalse. For example, String label = (score >= 50) ? "Pass" : "Fail"; assigns "Pass" if score is at least 50, otherwise "Fail".
Interview tip: Operator precedence is a common exam topic. Multiplication and division have higher precedence than addition and subtraction. Relational operators have higher precedence than logical operators. When in doubt, use parentheses to make precedence explicit and code intention clear.