Chapter 05 of 21
Chapter 05 β€” Phase 1: Fundamentals
Operators & Expressions
Operators are the verbs of Java β€” they perform actions on data. Master every operator, understand short-circuit evaluation, and learn operator precedence so you never misread an expression again.
~50 min read
8 Operator Types
7 MCQs
25 Practice Problems
⚑
5.1 β€” ConceptWhat is an Operator?

An operator is a special symbol that tells Java to perform a specific action on one or more values (called operands). The combination of operators and operands forms an expression. Every expression evaluates to a single value.

Analogy β€” Kitchen Tools

Operands are ingredients (5, 3, "Hello"). Operators are the kitchen tools that do something with them: + is the mixer (combines), - is the knife (subtracts), * is the oven (multiplies). The result is the final dish β€” the evaluated value of the expression.

Expression: 5 + 3 * 2 ↑ ↑ ↑ operand operator operand An expression always evaluates to a VALUE: 5 + 3 * 2 β†’ 11 (number) 10 > 5 β†’ true (boolean) "Hi" + "!" β†’ "Hi!" (String) a = 5 β†’ 5 (assignment returns the value assigned)

Java operators are grouped into 8 categories. We will cover each one in depth.

βž•
5.2 β€” Category 1Arithmetic Operators

These perform standard mathematical operations. They work on numeric types (byte, short, int, long, float, double).

Arithmetic Operators β€” Complete
int a = 17, b = 5;

System.out.println(a + b);   // 22  β€” addition
System.out.println(a - b);   // 12  β€” subtraction
System.out.println(a * b);   // 85  β€” multiplication
System.out.println(a / b);   // 3   β€” INTEGER division (truncated!)
System.out.println(a % b);   // 2   β€” modulus (remainder: 17 = 5Γ—3 + 2)

// Result type follows the "larger" operand type:
System.out.println(10 + 3.5);  // 13.5 (double β€” int widened)
System.out.println(7 + 3);     // 10   (int)
System.out.println(7.0 + 3);   // 10.0 (double)

Integer Division β€” The #1 Beginner Trap

When both operands are integers, the division result is also an integer β€” the decimal part is silently dropped. This surprises nearly every beginner.

Integer Division β€” The Trap
// int / int = int  (decimal silently dropped)
System.out.println(7 / 2);      // 3  (NOT 3.5!)
System.out.println(1 / 4);      // 0  (NOT 0.25!)
System.out.println(9 / 10);     // 0  (NOT 0.9!)

// FIX 1: make one operand a double literal
System.out.println(7.0 / 2);    // 3.5 βœ“
System.out.println(7 / 2.0);    // 3.5 βœ“

// FIX 2: cast one operand to double
int x = 7, y = 2;
double result = (double) x / y;  // 3.5 βœ“  β€” cast BEFORE dividing
double wrong  = (double)(x / y); // 3.0 βœ—  β€” divides first, THEN casts!
Cast BEFORE Dividing, Not After

(double)(x / y) first computes integer division (3), then casts to double (3.0). Still wrong! Always cast BEFORE the division: (double)x / y makes x a double first, forcing double division.

Modulus % β€” Remainder Operator

The % operator returns the remainder after integer division. It is one of the most useful operators in programming.

Modulus β€” Uses & Examples
System.out.println(17 % 5);   // 2  (17 = 5Γ—3 + 2)
System.out.println(10 % 3);   // 1  (10 = 3Γ—3 + 1)
System.out.println(8  % 4);   // 0  (8 = 4Γ—2 + 0, exactly divisible)
System.out.println(3  % 7);   // 3  (3 < 7, so remainder IS 3)

// Real-world uses of %:
int n = 42;
boolean isEven = (n % 2 == 0);     // true β€” even/odd check
int lastDigit = n % 10;             // 2 β€” extract last digit
int secondLastDigit = (n / 10) % 10; // 4 β€” extract 2nd last digit

// Cycling / wrapping around (e.g., 7 days of week):
int day = 9;
int dayOfWeek = day % 7;  // 2 (day 9 β†’ day 2 in the week cycle)

// Negative modulus (Java keeps sign of dividend):
System.out.println(-7 % 3);  // -1 (not 2!) β€” sign follows -7
System.out.println(7 % -3);  // 1  β€” sign follows 7
βš–οΈ
5.3 β€” Category 2Relational (Comparison) Operators

Relational operators compare two values and always return a boolean result β€” either true or false. They are essential for decision-making (if statements, loops).

Relational Operators
int a = 10, b = 20;

System.out.println(a == b);  // false β€” equal to (NOTE: == not =)
System.out.println(a != b);  // true  β€” not equal to
System.out.println(a >  b);  // false β€” greater than
System.out.println(a <  b);  // true  β€” less than
System.out.println(a >= b);  // false β€” greater than or equal
System.out.println(a <= b);  // true  β€” less than or equal
System.out.println(a == 10); // true  β€” a equals 10

// Store result in boolean variable:
boolean isAdult = (a >= 18);  // false (10 is not >= 18)
boolean passed  = (a > 5);    // true  (10 > 5)
= vs == β€” The Most Common Bug in All of Programming

= is the assignment operator β€” it puts a value INTO a variable. == is the equality comparison β€” it checks if two values are equal and returns boolean. Writing if (x = 5) instead of if (x == 5) causes a compile error in Java (assignment doesn't return boolean). In C/C++ this is a silent bug β€” in Java, the compiler catches it.

🧩
5.4 β€” Category 3Logical Operators

Logical operators combine multiple boolean expressions into a single boolean result. Think of them as the words "AND", "OR", "NOT" in English sentences.

Logical Operators
boolean p = true, q = false;

// && (AND) β€” BOTH must be true
System.out.println(p && q);   // false (true AND false = false)
System.out.println(p && p);   // true  (true AND true  = true)

// || (OR) β€” AT LEAST ONE must be true
System.out.println(p || q);   // true  (true OR false = true)
System.out.println(q || q);   // false (false OR false = false)

// ! (NOT) β€” reverses the boolean
System.out.println(!p);       // false (!true = false)
System.out.println(!q);       // true  (!false = true)

// Real-world combined conditions:
int age = 25;
double income = 40000;
boolean loanEligible = (age >= 18) && (income >= 30000);  // true

int marks = 75;
boolean distinction = (marks >= 80) || (marks == 75);  // true (second part)

boolean notPassed = !(marks >= 50);  // false (marks IS >= 50)

Truth Tables

ABA && B
TTT
TFF
FTF
FFF
ABA || B
TTT
TFT
FTT
FFF
A!A
TF
FT

Short-Circuit Evaluation β€” Critical Concept

Java's && and || use short-circuit evaluation: they stop evaluating as soon as the result is determined. This is not just an optimization β€” it prevents errors and is tested in exams.

Short-Circuit β€” How and Why It Matters
// && SHORT-CIRCUIT: if LEFT is FALSE, RIGHT is NEVER evaluated
int n = 0;
if (n != 0 && 10/n > 1) {  // SAFE! 10/n never runs (n != 0 is false)
    System.out.println("safe");
}
// Without short-circuit: 10/0 would throw ArithmeticException

// || SHORT-CIRCUIT: if LEFT is TRUE, RIGHT is NEVER evaluated
int x = 5;
if (x > 0 || ++x > 0) {  // x > 0 is TRUE, so ++x is NEVER executed
    System.out.println(x);  // prints 5, NOT 6!
}

// Non-short-circuit versions: & and | (evaluate BOTH sides always)
if (n != 0 & 10/n > 1) { }  // DANGEROUS β€” evaluates both, throws exception
Short-Circuit Rules
  • false && anything β†’ always false. Right side never evaluated.
  • true || anything β†’ always true. Right side never evaluated.
  • Use & and | (no double) only when you need both sides evaluated (rare).
  • Place cheaper/safer conditions on the LEFT side of &&/||.
πŸ“
5.5 β€” Category 4Assignment Operators

The simple = assigns a value. Compound assignment operators combine a math operation with assignment β€” they are shorthand that makes code cleaner.

Assignment Operators β€” All Forms
int x = 10;   // simple assignment: x = 10

// Compound assignment operators:
x += 5;    // x = x + 5  β†’ x = 15
x -= 3;    // x = x - 3  β†’ x = 12
x *= 2;    // x = x * 2  β†’ x = 24
x /= 4;    // x = x / 4  β†’ x = 6
x %= 4;    // x = x % 4  β†’ x = 2

// Also works for strings:
String s = "Hello";
s += " World";  // s = "Hello World"

// Chained assignment (right to left):
int a, b, c;
a = b = c = 5;  // c=5 first, then b=5, then a=5 β€” all equal 5

// Compound with implicit narrowing cast:
byte byt = 10;
byt += 5;    // βœ“ implicit cast: equivalent to byt = (byte)(byt + 5)
// byt = byt + 5  would cause error (int result, needs explicit cast)
Hidden Benefit: Compound Operators Include Implicit Cast

byte b = 10; b += 5; works even though b + 5 produces an int. The += operator automatically includes a narrowing cast back to byte. This is different from b = b + 5 which would give a compile error without an explicit cast.

1️⃣
5.6 β€” Category 5Unary Operators

Unary operators work on a single operand. The most important ones are the increment and decrement operators β€” they are among the most heavily tested in Java exams.

Unary Operators
int x = 5;

// Unary plus and minus:
int pos = +x;   // +5 β€” no change (unary plus rarely used)
int neg = -x;   // -5 β€” negates the value

// Logical NOT:
boolean t = true;
boolean f = !t;  // false

Increment & Decrement β€” The Most Tested Operators

Pre vs Post β€” The Critical Difference

Pre-increment ++x: increment FIRST, then use the NEW value.
Post-increment x++: use the OLD value FIRST, then increment.

Both result in x being incremented β€” the difference is only what value is used in the expression at that moment.

Increment & Decrement β€” Deep Dive
// Standalone β€” pre and post produce IDENTICAL results:
int a = 5;
a++;    // a = 6 (post-increment standalone)
++a;    // a = 7 (pre-increment standalone)
a--;    // a = 6 (post-decrement)
--a;    // a = 5 (pre-decrement)

// In an expression β€” CRITICAL DIFFERENCE:
int x = 5;
int y = x++;  // POST: y gets old value (5), then x increments β†’ y=5, x=6

int p = 5;
int q = ++p;  // PRE: p increments first (6), then q gets new value β†’ q=6, p=6

// Tricky example frequently in exams:
int a2 = 5;
System.out.println(a2++);  // prints 5 (old value), then a2 becomes 6
System.out.println(a2);    // prints 6
System.out.println(++a2);  // a2 becomes 7 first, then prints 7
System.out.println(a2);    // prints 7

// Complex expression (exam trap!):
int n = 5;
int result = n++ + ++n;
// Step 1: n++ uses 5 (old n), n becomes 6
// Step 2: ++n increments 6 to 7, uses 7
// result = 5 + 7 = 12,  n = 7
πŸ“‹ Pre vs Post Increment Dry Run
Coden beforeExpression valuen after
int n=5; int y=n++;5y = 5 (old n)n = 6
int n=5; int y=++n;5y = 6 (new n)n = 6
int n=5; int y=n--;5y = 5 (old n)n = 4
int n=5; int y=--n;5y = 4 (new n)n = 4
int n=5; println(n++);5prints 5n = 6
int n=5; println(++n);5prints 6n = 6
πŸ’»
5.7 β€” Category 6Bitwise Operators

Bitwise operators work directly on the binary (bit-level) representation of integers. Important for exams and low-level programming.

OperatorNameActionExampleResult
&Bitwise AND1 only if both bits are 15 & 31 (0101 & 0011 = 0001)
|Bitwise OR1 if at least one bit is 15 | 37 (0101 | 0011 = 0111)
^Bitwise XOR1 if bits are different5 ^ 36 (0101 ^ 0011 = 0110)
~Bitwise NOTFlips all bits~5-6
<<Left ShiftShift bits left (Γ—2 per shift)5 << 110
>>Right ShiftShift bits right (Γ·2 per shift)10 >> 15
>>>Unsigned Right ShiftShifts without sign extension-1 >>> 1Integer.MAX_VALUE
Bitwise β€” Examples with Binary
// 5 = 0101,  3 = 0011
System.out.println(5 & 3);   // 1  (0101 & 0011 = 0001)
System.out.println(5 | 3);   // 7  (0101 | 0011 = 0111)
System.out.println(5 ^ 3);   // 6  (0101 ^ 0011 = 0110)
System.out.println(~5);      // -6 (flip all bits of 5)

// Bit shifting (fast multiply/divide by powers of 2):
System.out.println(5 << 1);  // 10  (5 Γ— 2ΒΉ)
System.out.println(5 << 2);  // 20  (5 Γ— 2Β²)
System.out.println(20 >> 2); // 5   (20 Γ· 2Β²)

// Practical use: check if number is even (fast even/odd):
int n = 42;
boolean isEven = (n & 1) == 0;  // true β€” faster than n%2==0
❓
5.8 β€” Category 7Ternary Operator

The ternary operator is Java's shorthand for a simple if-else. It is the only three-operand operator in Java. Syntax: condition ? valueIfTrue : valueIfFalse

Ternary Operator β€” Complete Guide
// Basic ternary:
int a = 10, b = 20;
int max = (a > b) ? a : b;      // max = 20
int min = (a < b) ? a : b;      // min = 10
String result = (a % 2 == 0) ? "Even" : "Odd";  // "Even"

// Equivalent if-else:
int max2;
if (a > b) { max2 = a; } else { max2 = b; }

// Ternary inside println:
System.out.println("Pass or Fail: " + (a > 50 ? "Pass" : "Fail"));

// Nested ternary (use sparingly β€” hurts readability):
int score = 75;
String grade = score >= 90 ? "A"
              : score >= 80 ? "B"
              : score >= 70 ? "C"
              : "F";
System.out.println(grade);  // "C"

// Max of three numbers using nested ternary:
int x = 5, y = 9, z = 3;
int maxThree = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
// maxThree = 9
πŸ”—
5.9 β€” Category 8String Concatenation with +

The + operator is overloaded in Java β€” it means addition for numbers AND concatenation (joining) for Strings. The rules for mixed expressions are a favourite exam topic.

String Concatenation Rules
// String + anything = String (left to right evaluation)
System.out.println("Hello" + " World");  // "Hello World"
System.out.println("Age: " + 20);        // "Age: 20" (int→String)
System.out.println("Pi: " + 3.14);      // "Pi: 3.14"

// TRICKY: + is evaluated LEFT TO RIGHT
System.out.println(1 + 2 + "3");   // "33"  (1+2=3, then "3"+"3"="33")
System.out.println("1" + 2 + 3);   // "123" ("1"+2="12", "12"+3="123")
System.out.println(1 + 2 + 3);    // 6     (all ints: 1+2+3=6)

// Use () to force desired evaluation order:
System.out.println("Sum: " + (1 + 2 + 3));  // "Sum: 6" (brackets first)

// Char concatenation β€” VERY tricky:
System.out.println('A' + 'B');    // 131  (char + char = int! 65+66)
System.out.println("" + 'A' + 'B'); // "AB"  (empty String forces concatenation)
πŸ†
5.10 β€” Critical RuleOperator Precedence & Associativity

When an expression has multiple operators, Java uses operator precedence to determine which operations to perform first β€” exactly like BODMAS/PEMDAS in mathematics. Higher precedence = evaluated first.

1
() [] . method calls
Highest β€” parentheses, array access, member access
2
++ -- ! ~ (unary -) (type)
Unary operators β€” right to left
3
* / %
Multiplicative β€” left to right
4
+ -
Additive β€” left to right
5
<< >> >>>
Shift operators β€” left to right
6
< > <= >= instanceof
Relational β€” left to right
7
== !=
Equality β€” left to right
8
&
Bitwise AND
9
^
Bitwise XOR
10
|
Bitwise OR
11
&&
Logical AND
12
||
Logical OR
13
?:
Ternary β€” right to left
14
= += -= *= /= %= <<= >>= &= ^= |=
Lowest β€” assignment β€” right to left

Precedence Examples β€” Step by Step

Precedence β€” Trace Each Expression
// Example 1:
int r = 2 + 3 * 4 - 8 / 2;
// Step 1: * and / (same level, left to right): 3*4=12, 8/2=4
// Step 2: + and - (left to right): 2+12=14, 14-4=10
// r = 10

// Example 2:
boolean b = 5 + 3 > 6 && 10 - 4 == 6;
// Step 1: + and -: 5+3=8, 10-4=6
// Step 2: > and ==: 8>6 is true, 6==6 is true
// Step 3: &&: true && true = true
// b = true

// Example 3:
int x = 5;
int r2 = x++ * 2 + ++x;
// Step 1: x++ uses 5 (post), x becomes 6
// Step 2: 5 * 2 = 10
// Step 3: ++x increments 6 to 7, uses 7
// Step 4: 10 + 7 = 17
// r2 = 17, x = 7

// Example 4 β€” mixing + and String:
System.out.println(2 + 3 + " apples");   // "5 apples"
System.out.println("apples: " + 2 + 3); // "apples: 23" (NOT "apples: 5"!)
System.out.println("sum: " + (2+3));    // "sum: 5" (brackets force addition first)
Golden Rule β€” When in Doubt, Use Parentheses

Don't rely on memorizing all 14 precedence levels. When you're unsure, just use parentheses () to make the intended order explicit. This also makes your code more readable. (a + b) * (c - d) is clearer than relying on precedence.

🚫
5.11 β€” Watch OutMost Common Operator Mistakes
Top 8 Operator Mistakes
  1. = instead of == β€” Assignment vs comparison. if (x = 5) is an error in Java (compile error). Always use == to compare.
  2. Integer division β€” 7/2 gives 3, not 3.5. Cast to double first: (double)7/2.
  3. Post vs pre increment in expressions β€” y = x++ gives old x. y = ++x gives new x. Know the difference cold.
  4. Short-circuit side effects β€” x > 0 || ++count > 0 β€” if x>0, ++count never runs. Avoid side effects in short-circuit expressions.
  5. String + int confusion β€” "Value: " + 1 + 2 gives "Value: 12". Use "Value: " + (1+2) for "Value: 3".
  6. char arithmetic becomes int β€” 'A' + 1 gives 66, not 'B'. Cast back: (char)('A' + 1).
  7. Negative modulus β€” -7 % 3 gives -1 in Java, not 2. The sign follows the dividend.
  8. Cast placement for division β€” (double)(x/y) β‰  (double)x/y. First casts after integer division; second forces double division.
πŸ”
5.12 β€” TraceDry Run β€” Predict Output
Predict All Outputs Before Revealing

Program 1:

Predict
int a = 5, b = 5;
int c = a++ + ++b;
System.out.println(a + " " + b + " " + c);
Output: 6 6 11

Trace: a++ uses old a(5), then a becomes 6. ++b increments b to 6 first, uses 6. c = 5 + 6 = 11. Final: a=6, b=6, c=11.

Program 2:

Predict
System.out.println(10 + 20 + "30");
System.out.println("10" + 20 + 30);
System.out.println(10 + (20 + "30"));
3030
102030
12030

Trace 1: 10+20=30 (both ints), then "30"+"30"="3030". Trace 2: "10"+20="1020", "1020"+30="102030". Trace 3: inside brackets: 20+"30"="2030". Then: 10+"2030"="102030" β€” wait, no. 10 is int, "2030" is String. 10+"2030"="102030". Actually: 10+("2030") = "10"+"2030" = "102030". Let me recheck: 10 + "2030" β€” int + String = String: "102030". Yes.

Program 3:

Predict
int x = 10;
boolean r = (x > 5) || (++x > 0);
System.out.println(x + " " + r);
Output: 10 true

Short-circuit: (x > 5) = (10 > 5) = true. Since left side of || is true, the right side (++x > 0) is NEVER evaluated. So x remains 10, not 11. r = true.
Memory Tips β€” Chapter 5
  • Precedence mnemonic: "Unary Makes Additions Seem Ridiculously Easy And Logical" β†’ Unary, Multiplicative, Additive, Shift, Relational, Equality, And (bitwise), Logical
  • Short-circuit: "&& stops at first FALSE. || stops at first TRUE." β€” like a security guard: && checks everyone (strict), || lets first good one in (lenient).
  • Post vs pre: "POST = pay AFTER. PRE = pay BEFORE." Post-increment: use first, pay (increment) later. Pre-increment: pay first, use after.
  • Integer division: "Two integers fighting for division lose the decimal in the battle." Cast to double to save it.
  • String + int: "If String is at the party, everything becomes a String." Once Java sees a String, + means concatenation.
πŸ“
5.13 β€” ExamUniversity Exam Preparation
3 Marks β€” Explain

Q: What is short-circuit evaluation in Java? Explain with an example showing why it is useful.

Answer: Short-circuit evaluation means that in a logical expression with && or ||, the second operand is only evaluated if necessary. For &&: if the first operand is false, the result is always false regardless of the second β€” so Java skips evaluating the second. For ||: if the first operand is true, the result is always true β€” so the second is skipped. Example: if (n != 0 && 10/n > 1) β€” if n is 0, the second condition (10/n) is never evaluated, preventing a division-by-zero ArithmeticException. This makes short-circuit evaluation both a performance optimization AND a safety mechanism.

4 Marks β€” Output Prediction

Q: What is the output of the following? Show step-by-step working.

Exam Question
int a = 5;
System.out.println(a++);
System.out.println(++a);
System.out.println(a-- + --a);
System.out.println(a);
Output: 5 / 7 / 12 / 5

Line 1: a++ β€” prints old a (5), then a becomes 6.
Line 2: ++a β€” increments a from 6 to 7, prints 7. a=7.
Line 3: a-- β€” uses old a (7) in expression, then a becomes 6. --a β€” decrements a from 6 to 5, uses 5. Expression: 7 + 5 = 12. a=5.
Line 4: prints a = 5.

MCQ Bank

Q1.What is the output of: System.out.println(7 / 2);
A3.5
B3
C3.0
D4
βœ“ Integer / Integer = Integer. 7/2 = 3 (decimal .5 is silently dropped). To get 3.5, use: 7.0/2 or (double)7/2.
Q2.What is the output of: int x=5; System.out.println(x++ + " " + ++x);
A5 6
B5 7
C6 7
D6 6
βœ“ x++ uses old x (5) in expression, then x becomes 6. ++x increments x from 6 to 7, uses new value 7. Output: "5 7".
Q3.What is -7 % 3 in Java?
A2
B-1
C1
D-2
βœ“ In Java, the sign of the modulus result follows the sign of the DIVIDEND (left operand). -7 = 3Γ—(-2) + (-1). The remainder is -1. Different languages handle negative modulus differently β€” Java always follows the dividend's sign.
Q4.Given int x=5; boolean r = (x > 10) && (++x > 0); What is x after this statement?
A5 (unchanged)
B6
C7
DDepends on JVM
βœ“ Short-circuit with &&: (x > 10) = (5 > 10) = false. Since left side is false, the right side (++x > 0) is NEVER evaluated. x remains 5. r = false.
Q5.What is the output of: System.out.println("a" + 1 + 2);
Aa3
Ba12
C3a
D12a
βœ“ Evaluated left to right. "a" + 1 = "a1" (String concatenation). "a1" + 2 = "a12". If you wanted "a3", use: "a" + (1 + 2).
Q6.What is the ternary expression for: "return max of a and b"?
Aa ? b : a > b
B(a > b) ? a : b
Ca > b ? b : a
D(a < b) ? a : b
βœ“ Ternary: condition ? valueIfTrue : valueIfFalse. If a > b is true, a is the max. If false, b is the max. So: (a > b) ? a : b.
Q7.What is the output of: System.out.println(5 & 3);
A1
B7
C6
D15
βœ“ Bitwise AND: 5=0101, 3=0011. AND operation: 0101 & 0011 = 0001 = 1. Both bits must be 1 for the result to be 1.
Quick Revision β€” Chapter 5
Operators: arithmetic (+,-,*,/,%), relational (==,!=,>,<,>=,<=), logical (&&,||,!), assignment (=,+=,-=...), unary (++,--,!,-), bitwise (&,|,^,~,<<,>>), ternary (?:), string (+).
Integer division: int/int = int (decimal dropped). Cast to double BEFORE dividing: (double)x/y.
% modulus: gives remainder. Sign follows dividend. Uses: even/odd, last digit, cycling.
Post-increment x++: use old value, then increment. Pre-increment ++x: increment first, use new value.
Short-circuit &&: skips right if left is false. ||: skips right if left is true. Prevents errors and side effects.
String + number: left-to-right, once a String appears, subsequent + is concatenation. Use () to force addition.
Ternary: condition ? trueValue : falseValue β€” compact if-else. Returns a value.
Precedence: () β†’ unary β†’ * / % β†’ + - β†’ shifts β†’ relational β†’ == != β†’ bitwise β†’ && β†’ || β†’ ?: β†’ assignment.
When in doubt about precedence: use parentheses for clarity and correctness.
πŸ’ͺ
5.14 β€” PracticePractice Problems

Easy

P5.1
Arithmetic Playground
Given a=17, b=5. Compute and print: sum, difference, product, integer quotient, real quotient (as double), and remainder. Label each result.
Easy
P5.2
Even/Odd Checker
Read an integer. Using the modulus operator and ternary, print "Even" or "Odd" in one statement.
Easy
P5.3
Digit Extractor
Given number 4827, extract and print: last digit, tens digit, hundreds digit, thousands digit using / and % operators only.
Easy
P5.4
Truth Table Printer
Declare boolean a=true, b=false. Print results of: a&&b, a||b, !a, !b, a&&!b, !a||b in a formatted table.
Easy
P5.5
Compound Assignment
Start with x=100. Apply these in order: +=25, -=15, *=2, /=3, %=7. Print x after each operation. Show the math.
Easy
P5.6
Max of Three
Using ONLY ternary operators (no if-else, no Math.max), find the maximum of three integers a, b, c.
Easy
P5.7
Increment Predict
Before running, manually predict the value of a, b, and result for: int a=3,b=4; int result=a++ + ++b + a; Verify by running.
EasyPredict
P5.8
Bitwise Practice
Compute 5&3, 5|3, 5^3, ~5, 5<<1, 5>>1. Write the binary representation of each input next to the result.
Easy

Medium

P5.9
Expression Evaluator
Without running, evaluate step-by-step: 3 + 4 * 2 - 8 / 4 % 3 + 1. Show every step using operator precedence rules. Then verify.
MediumPredict
P5.10
Short-Circuit Safety
Write a program where short-circuit evaluation prevents a divide-by-zero. Then deliberately remove the safety condition and observe the exception.
Medium
P5.11
Loan Eligibility
Using only logical operators: print eligibility message for applicants. Eligible if: (age >= 18) AND (income >= 25000) AND (NOT bankrupt). Test with various combinations.
Medium
P5.12
Clock Arithmetic
Use modulus to simulate a clock. Given current hour (0-23) and hours to add, compute the new hour (stays in 0-23 range). Example: 22 + 5 = 3 (next day 3AM).
Medium
P5.13
String + Trap
Predict the output of 6 different expressions mixing int + String + int in different orders. Write your predictions first, then run to verify. Explain each result.
MediumPredict
P5.14
Grade Calculator Ternary
Using nested ternary ONLY, convert a numeric score (0-100) to a letter grade: A+(95+), A(85+), B(75+), C(65+), D(55+), F(below 55).
Medium

Hard

P5.15
Swap Without Variable
Swap two integers a and b WITHOUT using a third temporary variable. Use: (1) arithmetic trick (a = a+b; b = a-b; a = a-b), and (2) XOR trick. Prove both work.
Hard
P5.16
Bit Flag System
Use bit flags to store multiple boolean states in one int. Assign: READ=1 (bit 0), WRITE=2 (bit 1), EXECUTE=4 (bit 2). Write methods to set, clear, and check each permission using bitwise operators.
Hard
P5.17
Operator Priority Mystery
Predict the output of this without running: int a=1; int b=a++ + a++ + ++a; System.out.println(a+" "+b); Trace every step. Then verify.
HardPredict
P5.18
Power of Two Checker
Using only bitwise operators, write an expression that returns true if a number is a power of 2. Hint: a power of 2 in binary has exactly one 1-bit. Think about what n & (n-1) gives.
Hard
Chapter 5 Challenge

True operator mastery β€” no IDE, no hints.

  • Write from memory: the complete operator precedence table (14 levels) without looking.
  • Trace without running: int x=5; int y = x++ * 2 + ++x - x-- + --x; println(x+" "+y);
  • Research: What is the difference between && and &? When would you intentionally use & instead of &&? Write a practical example.
  • Challenge: Using ONLY bitwise operators (no +, -, *, /), add two integers. Research "bitwise addition" and implement it.