Java📅 Day 5

Operators in Java

Arithmetic, relational, logical, assignment, bitwise and ternary operators — with precedence rules.

🎯

Learning objectives

  • Use arithmetic and assignment operators correctly
  • Apply relational and logical operators for conditions
  • Understand operator precedence and short-circuit evaluation

💡 Key points

  • 5 arithmetic: + - * / % (modulo returns remainder)
  • 6 relational: == != < > <= >= — always return boolean
  • 3 logical: && || ! — && and || use short-circuit
  • Assignment shortcuts: += -= *= /= %=
  • Ternary: condition ? valueIfTrue : valueIfFalse — inline if/else

💻 Code examples(4)

#1Arithmetic + integer division trap
java
int a = 7, b = 2;
System.out.println(a / b);   // 3 (integer division!)
System.out.println(a % b);   // 1 (remainder)
System.out.println(a * 1.0 / b);  // 3.5 (force double)
int / int gives int — fractional part discarded. Cast one operand to double for real division.
#2Logical short-circuit
java
int x = 0;
if (x != 0 && 10 / x > 1) {
    // second condition never evaluated when x == 0
    // avoids ArithmeticException
}
&& stops evaluating once it hits false. || stops once it hits true. Guards against errors.
#3Ternary operator
java
int marks = 65;
String result = (marks >= 40) ? "Pass" : "Fail";
int max = (a > b) ? a : b;
Compact if/else for assignment. Overusing hurts readability — one level of nesting max.
#4Assignment shortcuts
java
int n = 10;
n += 5;   // n = n + 5 → 15
n *= 2;   // n = n * 2 → 30
n %= 7;   // n = n % 7 → 2

🎯 Practice

Q1. What is the result of 5 / 2 in Java?+

2 (integer division). To get 2.5 use 5.0 / 2 or (double)5/2.

Q2. Difference between == and .equals() for Strings?+

== compares references (same object in memory). .equals() compares contents. Use .equals() for String value comparison.

Q3. Predict output: int x = 5; System.out.println(x++ + ++x);+

12 — x++ uses 5 then increments (x=6), ++x increments first (x=7) then uses 7. Total = 5 + 7 = 12.

📝 Notes

Operator precedence (top to bottom)

| Level | Operators | |---|---| | Highest | () [] . | | Unary | ! ~ ++ -- +x -x | | Multiplicative | * / % | | Additive | + - | | Relational | < <= > >= instanceof | | Equality | == != | | Logical AND | && | | Logical OR | \|\| | | Ternary | ? : | | Assignment | = += -= *= /= %= |

When unsure — use parentheses. Compiler doesn't care; readers do.

Bitwise operators

  • & AND, | OR, ^ XOR, ~ NOT
  • << left shift, >> right shift, >>> unsigned right shift

Used for flags, low-level tricks. Rare in day-to-day code — safe to skip on first read.