Skip to content
notes.vinhnq.com

Search

Java CoreJunior19 min read

Java basics: operators, if and switch

Review 17 cards
On this page

Java basics series: 1. JVM and JDK · 2. Hello World and the three kinds of errors · 3. Variables and types · 4. Operators and branching · 5. Loops and methods · 6. Arrays and strings · 7. Console and text files · 8. Byte streams and serialization

Variables only hold data; operators and conditionals decide what the program does with it, and this is exactly where interview puzzles aim: x = x++, Integers compared with ==, short s = s + 1, a ternary that throws NullPointerException. After reading, you’ll be able to work out bitwise operations by hand, avoid those traps and pick correctly between if and switch. Read variables and data types first; next up is loops and methods.

At a glance:

mindmap
  root((Operators and branching))
    Arithmetic
      Integer division truncates to 0
      Remainder takes dividend sign
      Overflow wraps around
    == on objects compares addresses
    && and || short-circuit
    a++ returns old value
    Branching
      if: any condition
      switch: specific values

1. Operators

Key idea: Java operators work on concrete types (a 32-bit int, objects as references), so results sometimes differ from paper math. Most traps are in integer division, == on objects, ++ and overflow.

Arithmetic and assignment

int a = 17, b = 5;
a + b;   // 22
a - b;   // 12
a * b;   // 85
a / b;   // 3   (integer division)
a % b;   // 2   (remainder)
-17 / 5; // -3  (truncates toward zero)
-17 % 5; // -2  (the remainder takes the sign of the dividend)
Math.floorMod(-17, 5); // 3, handy for circular indexes and hash buckets

int x = 10;
x += 3;  // x = x + 3  -> 13
x -= 1;  // 12
x *= 2;  // 24
x /= 5;  // 4
x %= 3;  // 1

Compound assignment (+=, *=…) includes a hidden cast: short s = 1; s += 5; compiles, but s = s + 5; doesn’t, because s + 5 is an int. In arithmetic, byte, short and char are always promoted to int first.

Comparison and logic

Operator Meaning
==, != equal, not equal
>, >=, <, <= greater, greater or equal, less, less or equal
&& AND, short-circuits: if the left side is false, the right side is never evaluated
|| OR, short-circuits: if the left side is true, the right side is never evaluated
! NOT
int score = 72;
boolean passed = score >= 50;                 // true
boolean excellent = score >= 90 && passed;    // false
boolean retry = !passed || score < 75;        // true

// Short-circuiting protects you from a NullPointerException:
if (user != null && user.isActive()) { ... }

Increment and decrement: prefix vs postfix

Expression (start with a = 5) Order of operations Result
b = a++ assign b = a first, then increment a b = 5, a = 6
b = ++a increment a first, then assign a = 6, b = 6
b = a-- assign first, then decrement b = 5, a = 4
b = --a decrement first, then assign a = 4, b = 4

On their own (a++; or ++a;), both forms do the same thing. A popular puzzle: after int x = 5; x = x++;, x is still 5. The old value is computed first, x becomes 6, and then the old value is written back into x.

One of the slide comments is wrong: the example g = f-- is annotated as “f = f - 1; g = f”. It is really g = f; followed by f = f - 1 (the printed output, g : 2, f : 1, is the correct one).

Bits, bytes and binary

  • 1 byte = 8 bits. Lowercase b means bit, uppercase B means byte. A 100 Mbps link moves 100 megabits per second, roughly 12.5 MB per second.
  • SI prefix: 1 KB = 1000 B. Binary prefix: 1 KiB = 1024 B. RAM and the JVM’s -Xmx512m use powers of 1024. The slides only mention 1 KB = 1000 B, which is half the story.

Binary to decimal: multiply each bit by the power of two for its position (counting from the right, starting at 0) and add them up: 1101₂ = 8 + 4 + 0 + 1 = 13.

Decimal to binary: keep dividing by 2, write down the remainders, and read them bottom-up: 13 → 6 r1 → 3 r0 → 1 r1 → 0 r1 gives 1101.

More base conversions: 1101₂, 1010₂, 11011011₂ and 47

With every power written out: 1101₂ = 1·2³ + 1·2² + 0·2¹ + 1·2⁰ = 8 + 4 + 0 + 1 = 13.

The slide’s quiz, what is 1010₂: 0·2⁰ + 1·2¹ + 0·2² + 1·2³ = 0 + 2 + 0 + 8 = 10. A longer one: 11011011₂ = 128 + 64 + 16 + 8 + 2 + 1 = 219 (the zero bits, worth 32 and 4, are skipped).

For 47: 47 → 23 r1 → 11 r1 → 5 r1 → 2 r1 → 1 r0 → 0 r1, read bottom-up: 101111₂. Check: 32 + 8 + 4 + 2 + 1 = 47.

Ternary, instanceof and bitwise operators

String label = stock > 0 ? "In stock" : "Sold out";

Object o = "hello";
if (o instanceof String s && s.length() > 3) {   // pattern matching, Java 16+
    System.out.println(s.toUpperCase());
}

int flags = 0b0101;
flags & 0b0100;   // AND: test a bit
flags | 0b0010;   // OR: set a bit
flags ^ 0b0001;   // XOR: toggle a bit
~flags;           // NOT
1 << 10;          // 1024; shifting left multiplies by 2^n
-16 >> 2;         // -4; arithmetic shift keeps the sign
-16 >>> 28;       // 15; logical shift fills with zeros

Bitwise operators show up in permission bitmasks, feature flags, hash functions (HashMap spreads hashes with h ^ (h >>> 16)), and the power-of-two check (n & (n - 1)) == 0.

Bitwise operators work on each pair of bits in the same position: & gives 1 when both bits are 1, | when at least one is 1, ^ when they differ. With 5 = 0101 and 3 = 0011: 5 & 3 = 1, 5 | 3 = 7, 5 ^ 3 = 6, 5 << 2 = 20, 5 >> 2 = 1, ~5 = -6.

Working it out with a = 5, b = 3: truth table and shifts

In binary (showing only the last 4 bits; the rest are 0): 5 = 0101, 3 = 0011. The truth table:

bit x bit y x & y x | y x ^ y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
  0101 (5)      0101 (5)      0101 (5)
& 0011 (3)    | 0011 (3)    ^ 0011 (3)
  ----          ----          ----
  0001 = 1      0111 = 7      0110 = 6
  • 5 << 2: shift left by 2, 0101 becomes 010100 = 20, i.e. 5 · 2².
  • 5 >> 2: shift right by 2, 0101 becomes 0001 = 1, i.e. 5 / 2² rounded down. The vacated bits on the left are filled with the sign bit: zeros for positive numbers, ones for negative ones, so -20 >> 2 == -5. >>> always fills with zeros.
  • ~5 == -6: see the pitfall right below.

Precedence (simplified)

() > postfix a++ > prefix ++a, !, casts > * / % > + - > << >> > < > instanceof > == != > & > ^ > | > && > || > ?: > =, +=…

When in doubt, add parentheses. A favorite trick question: "" + 1 + 2 is "12" but 1 + 2 + "" is "3", because + is evaluated left to right.

2. Branching

Key idea: if takes any condition, including ranges; switch matches specific values or types. In new code prefer switch expressions, because they never fall through and the compiler checks every case is covered.

if / else if / else

static String classify(int temperature) {
    if (temperature < 0) {
        return "Freezing";
    } else if (temperature < 25) {
        return "Mild";
    } else {
        return "Hot";
    }
}

Conditions are checked from top to bottom and only one branch runs. Real code often uses guard clauses (early exits): return or throw at the top of the method on invalid input, so the main logic is not buried in nested ifs.

static BigDecimal discount(Order order) {
    if (order == null) throw new IllegalArgumentException("order is required");
    if (!order.isPaid()) return BigDecimal.ZERO;
    // the main logic is not nested inside any if
    return order.total().multiply(new BigDecimal("0.05"));
}

The ternary operator

Use it for a short choice between two values. Don’t nest ternaries; they become unreadable fast.

switch: classic and modern

The classic form needs a break in every case. Forget one and execution falls through into the next case:

int month = 4;
int days;
switch (month) {
    case 2:
        days = 28;
        break;
    case 4: case 6: case 9: case 11:   // group cases that share the same handling
        days = 30;
        break;
    default:
        days = 31;
}

Switch expressions (Java 14+; Java 12–13 only had them as a preview, so material saying “since Java 12” is slightly off) use arrows, never fall through and produce a value. Over enums or sealed types (types that allow only a fixed list of subclasses), the compiler forces you to cover every case:

String dayName = switch (day) {
    case 1 -> "Sunday";
    case 2, 3, 4, 5, 6, 7 -> "Weekday " + day;
    default -> throw new IllegalArgumentException("Invalid day: " + day);
};

Types you can switch on: byte, short, char, int and their wrappers, String, enums, and since Java 21 any reference type (with patterns). long, float, double and boolean can’t be used in a classic switch. case labels must be compile-time constants.

The slides list “var” among the supported types, but var is not a type; it is only a variable whose type is inferred as one of the types above.

Exercises

Each prompt is a short paraphrase. All solutions were run on JDK 21.

Group 3: operators and conditions

3.1. Declare a String and print it: String course = "Backend"; System.out.println(course);.

3.2. Say whether an integer is even or odd and whether it is positive or negative, one conclusion per line.

3.3. Print the sum, difference, product and quotient of two integers; the division needs a cast and a zero check.

3.4. Compare two numbers: Integer.compare(a, b) returns a negative number, 0 or a positive number; then use if/else if/else to print “a is larger”, “b is larger” or “they are equal”.

3.5. Perimeter and area of a rectangle with sides a and b: 2 * (a + b) and a * b. Validate a > 0 && b > 0 first.

3.6. Can three real numbers form a triangle (print YES/NO)?

3.7. Convert decimal ↔ binary, using the “divide by 2, keep the remainder” and “multiply by 2, add the bit” algorithms from the “Bits, bytes and binary” section above.

Solutions for group 3: 3.2, 3.3, 3.6, 3.7

3.2.

static String describeNumber(int n) {
    String parity = n % 2 == 0 ? "even" : "odd";    // use n % 2 != 0 for odd; n % 2 == 1 fails for negatives
    String sign = n > 0 ? "positive" : n < 0 ? "negative" : "zero";
    return parity + "\n" + sign;
}

The trap: -7 % 2 == -1, not 1, so checking n % 2 == 1 breaks for negative numbers.

3.3.

static void arithmetic(int a, int b) {
    System.out.println("Sum: " + ((long) a + b));          // widen to long to avoid overflow
    System.out.println("Difference: " + ((long) a - b));
    System.out.println("Product: " + ((long) a * b));
    if (b == 0) {
        System.out.println("Cannot divide by zero");
    } else {
        System.out.println("Quotient: " + (double) a / b);  // cast before dividing
    }
}

(double) a / b is not the same as (double) (a / b). The second form divides as integers first and only then casts, so the fraction is already gone.

3.6.

static boolean isTriangle(double a, double b, double c) {
    return a > 0 && b > 0 && c > 0 && a + b > c && a + c > b && b + c > a;
}
System.out.println(isTriangle(3, 4, 5) ? "YES" : "NO");

3.7.

static String toBinary(int n) {
    if (n == 0) return "0";
    StringBuilder sb = new StringBuilder();
    while (n > 0) { sb.append(n % 2); n /= 2; }
    return sb.reverse().toString();
}

static int fromBinary(String bits) {
    int result = 0;
    for (char c : bits.toCharArray()) {
        if (c != '0' && c != '1') throw new IllegalArgumentException("Not a binary digit: " + c);
        result = result * 2 + (c - '0');
    }
    return result;
}

Group 4: conditional exercises from the Hỏi Dân IT material

4.1. Grade a student from their average score (out of 10). 9 and above is Excellent, from 8 Very good, from 6.5 Good, from 5 Average, below 5 Weak, and anything outside [0, 10] is invalid.

4.2. Read a number from 1 to 7 and print the day of the week (1 is Monday); outside that range, print Invalid day number!.

Solutions for group 4: 4.1 and 4.2

4.1.

static String grade(double score) {
    if (!(score >= 0 && score <= 10)) return "Invalid";   // catches NaN too
    if (score >= 9) return "Excellent";
    if (score >= 8) return "Very good";
    if (score >= 6.5) return "Good";
    if (score >= 5) return "Average";
    return "Weak";
}
// 9.0 -> Excellent, 8.99 -> Very good, 4.9 -> Weak, 11 -> Invalid

The original table lists ranges such as “8.0 – 9.0” and “9.0 – 10.0”, so it’s unclear where exactly 9.0 belongs. When you code the conditions, always settle each range as half-open ([8, 9)); checking from the top down, each if then needs only a lower bound.

4.2.

static String dayName(int day) {
    return switch (day) {
        case 1 -> "Monday";
        case 2 -> "Tuesday";
        case 3 -> "Wednesday";
        case 4 -> "Thursday";
        case 5 -> "Friday";
        case 6 -> "Saturday";
        case 7 -> "Sunday";
        default -> "Invalid day number!";
    };
}

In real code, use java.time.DayOfWeek.of(day): it follows the same ISO-8601 convention (1 = Monday) and throws DateTimeException when out of range, so you don’t maintain the table yourself.

Remember

  • Can you explain why -7 % 2 == -1 and when you need Math.floorMod?
  • Can you explain why Integer 127 compared with == gives true but 128 gives false?
  • Can you compute 5 & 3, 5 >> 2 and ~5 by hand, and say why ~5 is negative?
  • Do you know why count++ is unsafe across threads and what to use instead?
  • Do you know when to use if, when a switch expression, and when to move to polymorphism?

Interview questions

Junior

What are 7 / 2, 7 % -2 and -7 / 2?

3, 1 and -3.

Integer division truncates toward zero, and the remainder takes the sign of the dividend. For a remainder that is never negative, use Math.floorMod.

What is the difference between a++ and ++a?

a++ evaluates to the value before the increment, ++a to the value after it.

Both add 1 to a. The difference only matters when they are part of a larger expression, such as b = a++.

What is the difference between && and & on booleans?

Both compute AND, but && short-circuits (if the left side is false, the right side is skipped) while & always evaluates both sides.

That’s why user != null && user.isActive() is safe while user != null & user.isActive() still throws NullPointerException when user is null. The same goes for || and |. On integers, & and | are bitwise operators.

Compute 5 & 3, 5 | 3, 5 ^ 3, 5 << 2, 5 >> 2 and ~5. Why is ~5 negative?

1, 7, 6, 20, 1, -6; ~5 is negative because flipping all 32 bits sets the sign bit.

5 = 0101 and 3 = 0011. 5 << 2 multiplies by 4, 5 >> 2 divides by 4 rounding down. In two’s complement, ~x == -x - 1.

Mid

Integer a = 128, b = 128; a == b: what does it return, and why?

false, because Integer.valueOf only caches -128 to 127, so 128 gives two distinct objects.

Autoboxing (wrapping an int into an Integer automatically) calls Integer.valueOf, and == compares references. Always compare wrappers with equals (or Objects.equals).

What do switch expressions (Java 14+) improve over the classic switch?

No fall-through, they produce a value, and the compiler checks exhaustiveness for enums and sealed types.

Several labels can share a case with commas. Java 21 adds pattern matching and when guards.

Does short s = 1; s = s + 1; compile? What about s += 1?

s = s + 1 doesn’t compile; s += 1 does.

s + 1 is an int and won’t narrow to short on its own. Compound assignment includes an implicit cast back to the left-hand type.

Senior

Is count++ on a field shared between threads safe?

No. It is a read, an add and a write; interleaved threads lose updates (a race condition).

volatile only guarantees visibility, not atomicity. Use AtomicInteger.incrementAndGet(), LongAdder for heavy write contention, or synchronized.

An if/else or switch chain on some “type” keeps growing. How would you refactor it?

The goal is that adding a new type doesn’t require editing existing code; pick polymorphism, a Map<Type, Handler> or a sealed interface depending on the case.

  • Polymorphism: one class per type implementing a shared interface, following the Open/Closed Principle.
  • A Map<Type, Handler> or a Strategy that Spring injects as a List<Handler>.
  • A sealed interface with pattern-matching switch, so the compiler enforces exhaustiveness.

Useful phrases for interviews

  • “For objects, == checks identity while equals checks logical equality, which is why comparing Integers with == breaks above 127.”
  • “I prefer guard clauses over deeply nested conditionals; they keep the happy path flat and readable.”
  • “With switch expressions over sealed types, the compiler tells me when I’ve forgotten a case.”
  • “count++ isn’t atomic; under concurrency I’d use an AtomicInteger or a LongAdder.”
  • “I’d use short-circuit evaluation here so the null check guards the method call.”
  • “The remainder takes the sign of the dividend, so for a circular index I use Math.floorMod.”
  • “Compound assignment hides an implicit narrowing cast, which is why s += 1 compiles but s = s + 1 doesn’t.”
  • “With pattern matching for switch, I branch on the type and bind the variable in one step.”
  • “Looking at the truth table, XOR is 1 only when the two bits differ, which is why it’s handy for toggling flags.”
  • “>> is an arithmetic shift that copies the sign bit, while >>> always shifts in zeros.”

Most of the diagrams in the slides come from Introduction to Java Programming and Data Structures by Y. Daniel Liang (11th edition), a good book if you want to read further.


Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.