Java Arithmetic, Assignment & Relational Operators

โ˜• Java 21+ LTS ๐ŸŸข Chapter 10 of 47 ๐Ÿ“‚ Phase 3: Operators and Input ๐Ÿ“… 2026 Edition
๐Ÿ“Œ Covered in this chapter:

Arithmetic Operators (+, -, *, /, %) ยท Integer Division vs Floating-Point ยท String Concatenation Nuances ยท Compound Assignment ยท Relational Operators

Deep dive into fundamental Java operators: arithmetic operations, integer division caveats, modulo arithmetic, string concatenation mechanics, shorthand compound assignments, and Boolean relational comparisons.

1. Arithmetic Operators (+, -, *, /, %)

Arithmetic operators perform standard mathematical operations on numeric data types:

OperatorNameSyntaxExampleResult
**`+`**
Addition | a + b | 10 + 5 | 15 | | - | Subtraction | a - b | 10 - 5 | 5 | | * | Multiplication | a * b | 10 * 5 | 50 | | / | Division | a / b | 10 / 4 (int) vs 10.0 / 4 | 2 vs 2.5 | | % | Modulus (Remainder) | a % b | 10 % 3 | 1 |

The Critical Integer Division Trap:

In Java, if both operands of a division operator are integers (byte, short, int, long), Java performs Integer Division, automatically discarding any decimal fraction:
int result1 = 7 / 2;     // Evaluates to 3 (decimal .5 discarded!)
double result2 = 7 / 2;   // Evaluates to 3.0 (division happened first as int!)
double result3 = 7.0 / 2; // Evaluates to 3.5 (one operand is double, so float division occurs)

2. String Concatenation with the `+` Operator

The + operator in Java is overloaded:
1. When used between two numbers, it performs Arithmetic Addition.
2. When at least one operand is a String, it converts the other operand to text and performs String Concatenation.

Left-to-Right Evaluation Order:

Because + evaluates from left to right:
System.out.println("Result: " + 10 + 20);   // Outputs: "Result: 1020"
System.out.println("Result: " + (10 + 20)); // Outputs: "Result: 30" (Parentheses force math first!)
System.out.println(10 + 20 + " is Total");  // Outputs: "30 is Total" (10+20 evaluated first)

3. Assignment & Compound Assignment Operators

The simple assignment operator (=) assigns the evaluated value on the right to the variable on the left.

Compound Assignment Operators combine arithmetic and assignment into one concise, optimized step:

Compound OperatorEquivalent SyntaxBehavior & Auto-Casting Feature
**`x += 5`**
x = (type)(x + 5) | Adds 5 to x and assigns back to x. Auto-casts to original type! | | x -= 5 | x = (type)(x - 5) | Subtracts 5 from x. | | x *= 5 | x = (type)(x * 5) | Multiplies x by 5. | | x /= 5 | x = (type)(x / 5) | Divides x by 5. | | x %= 5 | x = (type)(x % 5) | Computes x % 5 and stores remainder. |

The Secret Auto-Cast of Compound Operators:

byte b = 10;
// b = b + 5; // COMPILE ERROR: (b + 5) promotes to int, cannot assign int to byte
b += 5;       // WORKS! Equivalent to: b = (byte)(b + 5);

4. Relational (Comparison) Operators

Relational operators compare two values and always return a primitive boolean result (true or false):

OperatorMeaningExample (`a = 10, b = 20`)Result
**`==`**
Equal to | a == b | false | | != | Not equal to | a != b | true | | > | Greater than | a > b | false | | < | Less than | a < b | true | | >= | Greater than or equal to | a >= 10 | true | | <= | Less than or equal to | b <= 20 | true |

Beginner Example & Code Anatomy

โ˜• Main.java โ€” Chapter 10 Core Example
public class Main {
    public static void main(String[] args) {
        // 1. Arithmetic Operations
        int a = 25;
        int b = 4;

        System.out.println("--- Arithmetic Operators Demo ---");
        System.out.println("a + b = " + (a + b)); // 29
        System.out.println("a - b = " + (a - b)); // 21
        System.out.println("a * b = " + (a * b)); // 100
        System.out.println("a / b (Integer Division) = " + (a / b));       // 6
        System.out.println("a / b (Decimal Division) = " + ((double)a / b)); // 6.25
        System.out.println("a % b (Remainder)        = " + (a % b));       // 1

        // 2. Compound Assignment Operators
        int score = 100;
        score += 50;  // score = 150
        score *= 2;   // score = 300
        score -= 75;  // score = 225
        System.out.println("
Final Computed Score: " + score);

        // 3. Relational Comparisons
        int passingMark = 40;
        int studentScore = 78;
        boolean hasPassed = studentScore >= passingMark;
        boolean isPerfect = studentScore == 100;

        System.out.println("
--- Relational Checks ---");
        System.out.println("Student Passed Exam: " + hasPassed);
        System.out.println("Student Got 100%   : " + isPerfect);
    }
}
๐Ÿ’ป Program Console Output
--- Arithmetic Operators Demo --- a + b = 29 a - b = 21 a * b = 100 a / b (Integer Division) = 6 a / b (Decimal Division) = 6.25 a % b (Remainder) = 1 Final Computed Score: 225 --- Relational Checks --- Student Passed Exam: true Student Got 100% : false

๐Ÿ” Line-by-Line Code Explanation

(double)a / b

Explicitly casts variable 'a' to double before division, forcing floating-point division (6.25) instead of truncated integer division (6).

a % b

Modulus operator computes the integer remainder left over after dividing 25 by 4 (which is 1).

score += 50;

Compound addition assignment shorthand equivalent to score = score + 50.

boolean hasPassed = studentScore >= passingMark;

Evaluates whether 78 >= 40, assigning the boolean outcome true.

Practical Real-World Example

โ˜• PracticalApplication.java โ€” Industry Implementation
public class EvenOddModulusDemo {
    public static void main(String[] args) {
        int[] testNumbers = { 14, 27, 40, 99, 102 };

        System.out.println("=== Even / Odd Classification with Modulo (%) ===");
        for (int num : testNumbers) {
            boolean isEven = (num % 2 == 0);
            System.out.println("Number " + num + " is: " + (isEven ? "EVEN" : "ODD"));
        }
    }
}
๐Ÿ’ป Practical Console Output
=== Even / Odd Classification with Modulo (%) === Number 14 is: EVEN Number 27 is: ODD Number 40 is: EVEN Number 99 is: ODD Number 102 is: EVEN
โš ๏ธ Common Mistakes & Professional Best Practices
  • Forgetting parentheses in String concatenation: Writing "Sum: " + 10 + 20 outputs "Sum: 1020". Write "Sum: " + (10 + 20) to output "Sum: 30".
  • Using single equals (=) instead of double equals (==): "if (x = 5)" is an assignment error in Java. Comparison must always use "==".
  • Assuming (int / int) produces decimal: Writing "double ratio = 1 / 2;" stores 0.0, because 1/2 evaluates to 0 in integer math. Use "1.0 / 2.0".
๐ŸŽฏ Hands-on Coding Challenge

Test your understanding by writing the code directly in your editor or running in our online Java compiler:

โ˜• Challenge.java
// Coding Challenge:
// Given totalSeconds = 3850:
// 1. Calculate hours = totalSeconds / 3600
// 2. Calculate remainingSeconds = totalSeconds % 3600
// 3. Calculate minutes = remainingSeconds / 60
// 4. Calculate seconds = remainingSeconds % 60
// Output in format: "3850 seconds = 1 hr, 4 min, 10 sec"

public class Main {
    public static void main(String[] args) {
        int totalSeconds = 3850;
        // TODO: Compute hours, minutes, and seconds using / and %
        
    }
}

๐Ÿ’ก Frequently Asked Questions & Interview Insights

โ“ What happens when you divide a floating point number by zero (e.g. 10.0 / 0.0)?

Unlike integer division (which throws ArithmeticException: / by zero), floating-point division by zero produces "Infinity" or "-Infinity", and 0.0 / 0.0 produces "NaN" (Not a Number).

โ“ Can modulus (%) be used with negative numbers in Java?

Yes! In Java, the sign of the result of a % b matches the sign of the dividend (a). For example, -7 % 3 = -1, and 7 % -3 = 1.

โ“ Why do compound operators auto-cast?

Java language specification defines compound assignments with an implicit cast: "E1 op= E2" is defined as "E1 = (T)((E1) op (E2))", where T is the type of E1.

๐Ÿš€ Quick Chapter Recap

  • Integer division truncates decimals; cast one operand to double to preserve fractions.
  • + operator performs addition for numbers, but concatenation if either operand is a String.
  • Compound operators (+=, -=, etc.) automatically cast the evaluated result to the target type.
  • Relational operators (==, !=, >, <, >=, <=) evaluate to boolean true or false.
โ† Prev: 9. Type Casting & var Next: 11. Logical & Bitwise โ†’
OC
Curated by Our Compiler Java Technical Editorial Team
Published for 2026 Academic & Enterprise Reference ยท 100% Free & Open Access