Java Arithmetic, Assignment & Relational Operators
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:
| Operator | Name | Syntax | Example | Result |
|---|---|---|---|---|
| **`+`** |
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 Operator | Equivalent Syntax | Behavior & 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):
| Operator | Meaning | Example (`a = 10, b = 20`) | Result |
|---|---|---|---|
| **`==`** |
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
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);
}
}
๐ 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
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"));
}
}
}
- 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".
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// 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.