Java tutorials  /  Java Operators
Chapter 3 · Java

Java Operators

An operator in Java is a special symbol that performs specific operations on one, two, or three operands (variables and values), and returns a result. Java categorizes operators into several types including arithmetic, relational, logical, bitwise, assignment, and ternary/conditional operators.

Operators are like the verbs of a programming sentence — they tell Java what action to perform. If variables are the nouns holding data, operators are the actions: adding two numbers together (+), checking if one number is bigger than another (>), or deciding between two outcomes based on a condition (?:). Just like in math class, Java also follows a strict order of operations (precedence) when a statement uses multiple operators together.

Consider a ride-sharing app like Uber calculating a fare. Arithmetic operators calculate the base cost by multiplying distance by rate-per-km. Relational operators check if it's currently within 'peak hours' (comparing current time to a threshold). Logical operators combine multiple conditions, such as checking if it's both raining AND peak hours to apply a surge multiplier. The ternary operator might be used to quickly decide the final display message: 'surgeActive ? "Prices are higher due to demand" : "Standard pricing applies"'. This shows how a combination of operator types work together in a single real-world business calculation.

Operators are the fundamental building blocks that allow programs to perform calculations, make decisions, and manipulate data. Without operators, a program could only store static data with no way to transform it, compare it, or make logic-based decisions — which are the core capabilities that make programming useful for solving real problems like calculating totals, validating user input, or controlling program flow based on conditions.

  • Arithmetic Operators: Used to perform basic mathematical operations: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%), which returns the remainder of a division.
  • Relational (Comparison) Operators: Used to compare two values and return a boolean result: equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
  • Logical Operators: Used to combine multiple boolean expressions: logical AND (&&), logical OR (||), and logical NOT (!). The '&&' and '||' operators use short-circuit evaluation, skipping the second operand if the result is already determined by the first.
  • Assignment Operators: Used to assign values to variables, including the basic assignment (=) and compound assignment operators like +=, -=, *=, /=, and %=, which combine an operation with assignment in a single step.
  • Bitwise Operators: Operate directly on the individual bits of integer types, including AND (&), OR (|), XOR (^), complement (~), left shift (<<), and right shift (>>), commonly used in performance-critical or low-level applications.
  • Ternary (Conditional) Operator: A shorthand, single-line alternative to an if-else statement, using the syntax 'condition ? valueIfTrue : valueIfFalse', useful for concise conditional assignments.
// General operator usage: result = operand1 operator operand2; // Ternary operator syntax: variable = (condition) ? valueIfTrue : valueIfFalse;
A beginner wants to build a simple program that calculates whether a student has passed an exam (score >= 40), determines a letter grade using multiple conditions, and displays a pass/fail message using the most concise syntax possible. This requires combining relational, logical, and ternary operators effectively.
Arithmetic and Relational Operators in Action
This example calculates a student's average score using arithmetic operators and then checks if they passed using a relational operator.
Java
public class ExamResult { public static void main(String[] args) { int mathScore = 85; int scienceScore = 78; int average = (mathScore + scienceScore) / 2; boolean hasPassed = average >= 40; System.out.println("Average Score: " + average); System.out.println("Has Passed: " + hasPassed); } }
Average Score: 81 Has Passed: true
The '+' operator adds the two scores, and '/' divides the sum to calculate the average (note: since both operands are 'int', this performs integer division). The '>=' relational operator compares 'average' against 40 and returns a boolean value ('true' or 'false'), which is then stored directly in the 'hasPassed' variable.
Logical and Ternary Operators for Grade Calculation
This example combines logical operators to check multiple conditions and uses the ternary operator to assign a pass/fail message concisely.
Java
public class GradeChecker { public static void main(String[] args) { int attendance = 85; int examScore = 55; boolean isEligible = (attendance >= 75) && (examScore >= 40); String result = isEligible ? "Passed" : "Failed - Check Attendance or Score"; System.out.println("Eligible: " + isEligible); System.out.println("Result: " + result); } }
Eligible: true Result: Passed
The '&&' (logical AND) operator ensures 'isEligible' is only true if BOTH conditions (attendance >= 75 AND examScore >= 40) are true; if attendance were 70, the entire expression would short-circuit to false without needing to check examScore. The ternary operator then reads 'isEligible' and assigns 'Passed' or 'Failed...' to 'result' in a single concise line, replacing what would otherwise require a 4-line if-else block.
  • Confusing Assignment (=) with Equality (==): A very common beginner mistake is writing 'if (isActive = true)' instead of 'if (isActive == true)' inside a condition. In Java, this specific mistake usually causes a compile-time error if 'isActive' isn't a boolean already being assigned a boolean literal, but with boolean variables it can silently assign the value instead of comparing it, leading to logic bugs that are hard to trace, since the condition always evaluates based on the assigned value rather than the intended comparison.
  • Integer Division Truncation: Dividing two 'int' values, such as '7 / 2', results in '3' (not 3.5) because integer division in Java truncates any decimal remainder. Beginners expecting a precise decimal result must cast at least one operand to a 'double' first, e.g., '(double) 7 / 2', to get the correct result of 3.5.
  • Operator Precedence Confusion: Writing an expression like 'int result = 10 + 5 * 2;' expecting the answer '30' (evaluating left to right) but getting '20' instead, because multiplication has higher precedence than addition and is evaluated first (5 * 2 = 10, then 10 + 10 = 20). Beginners should use parentheses liberally, e.g., '(10 + 5) * 2', to make intended order of operations explicit and avoid relying purely on memorized precedence rules.
  • Not Understanding Short-Circuit Evaluation Side Effects: When using '&&' or '||' with method calls that have side effects (like incrementing a counter), beginners are often surprised when the second method call doesn't execute. For example, in 'if (false && incrementCounter())', 'incrementCounter()' is never called because '&&' short-circuits as soon as the first operand is false, since the overall result is already guaranteed to be false.
  • Use Parentheses to Clarify Complex Expressions: Even when you know operator precedence rules, use parentheses to make the intended order of operations explicit in complex expressions, such as '(a + b) * (c - d)'. This drastically improves code readability for other developers and reduces bugs from precedence misunderstandings.
  • Prefer Compound Assignment Operators for Conciseness: Use compound operators like 'count += 1;' instead of 'count = count + 1;' where appropriate, as they are more concise, slightly reduce the chance of typos in longer variable names, and are the conventional style expected in professional Java codebases.
  • Leverage Short-Circuit Evaluation for Null-Safety: Order logical conditions strategically to take advantage of short-circuiting for safety, such as writing 'if (obj != null && obj.getValue() > 0)' — placing the null check first ensures 'obj.getValue()' is never called on a null reference, preventing a NullPointerException.
  • Avoid Overusing the Ternary Operator for Complex Logic: While the ternary operator is great for simple, single-condition assignments, avoid nesting multiple ternary operators together (e.g., 'a > b ? x : a > c ? y : z'), as this quickly becomes hard to read. Use a standard if-else-if chain instead when the logic involves more than one condition.
What is the difference between '==' and '.equals()' when comparing values in Java, especially regarding operators?
The '==' operator, when used with primitive data types, compares actual values directly (e.g., '5 == 5' is true). However, when used with objects (like String or Integer), '==' compares object references — whether both variables point to the exact same memory location — not their actual content. The '.equals()' method, in contrast, is used specifically to compare the actual content/value of objects. For example, two separate String objects with the same text created using 'new String("test")' would return false with '==' but true with '.equals()', since '==' checks reference identity while '.equals()' checks logical value equality.
Explain short-circuit evaluation in Java with the '&&' and '||' operators, and why it matters.
Short-circuit evaluation means Java stops evaluating a logical expression as soon as the overall result is already determined. With '&&' (AND), if the first operand is false, the entire expression must be false, so the second operand is never evaluated. With '||' (OR), if the first operand is true, the entire expression must be true, so the second operand is skipped. This matters for both performance (avoiding unnecessary computation) and safety — it's commonly used to prevent errors, such as checking 'if (arr != null && arr.length > 0)', where checking 'arr.length' would throw a NullPointerException if 'arr' were null and evaluated regardless.
What is the output of the following code and why: 'System.out.println(5 + 3 + "Java" + 2 + 3);'?
The output is '8Java23'. Java evaluates the '+' operator strictly left to right. '5 + 3' are both integers, so they are added numerically first, producing '8'. Then '8 + "Java"' triggers string concatenation because one operand is now a String, producing the string '8Java'. From this point onward, every subsequent '+' operation treats both sides as string concatenation, so '"8Java" + 2' becomes '"8Java2"', and finally '+ 3' becomes '"8Java23"'. This demonstrates how operand order dramatically changes the result when mixing arithmetic and String concatenation with the same '+' operator.
Write a Java program that takes two integers, 15 and 4, and prints the result of their division and the remainder (modulus) separately.
public class DivisionRemainder { public static void main(String[] args) { int a = 15; int b = 4; System.out.println("Division: " + (a / b)); System.out.println("Remainder: " + (a % b)); } } // Output: // Division: 3 // Remainder: 3
What will be the output of the following code, and explain why? int x = 5; int y = 10; boolean result = (x > 3) || (y / 0 > 1); System.out.println(result);
The output will be 'true', with no exception being thrown. Even though 'y / 0' would normally throw an ArithmeticException, the '||' operator short-circuits: since '(x > 3)' evaluates to 'true' first, Java knows the overall OR expression must be true regardless of the second operand, so it never evaluates '(y / 0 > 1)' at all, completely avoiding the division-by-zero error.
Using the ternary operator, write a single line of code that assigns the string "Even" to a variable 'result' if a given integer 'num' is even, or "Odd" if it is odd.
String result = (num % 2 == 0) ? "Even" : "Odd"; // This uses the modulus operator (%) to check the remainder when divided by 2. If the remainder is 0, the number is even; otherwise, it's odd. The ternary operator then assigns the appropriate string based on this boolean condition in a single concise line.

Java operators — arithmetic, relational, logical, assignment, bitwise, and ternary — are the fundamental tools for performing calculations, comparisons, and decision-making within a program. Understanding operator precedence, integer division truncation, short-circuit evaluation, and the critical distinction between '==' and '.equals()' for objects are essential skills that prevent common bugs and form the logical backbone for control flow structures like if-else statements and loops.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.