← Back to Java series
Basics
Basics · Prerequisite: previous lecture

03. Operators and Expressions

Operators take operands and produce new values. Java's operators look familiar to anyone coming from C/C++, but watch out for **object comparison (`==` vs `.equals()`)** and **integer / floating-point division** — this lecture untangles both.

JavaJDKbasicsoperators and expressions
Duration
~1-1.5 hours
Level
📊 Beginner
Prerequisite
🎯 Previous lecture or equivalent knowledge
OUTCOME
Operators take operands and produce new values. Java's operators look familiar to anyone coming from C/C++, but watch out for **object comparison (`==` vs `.equals()`)** and **integer / floating-point division** — this lecture untangles both.

What you'll learn

  • 1Use arithmetic, comparison, logical, bitwise, ternary, and increment operators
  • 2Understand left-to-right evaluation when concatenating with `+`
  • 3Distinguish `==` from `.equals()`
  • 4Understand short-circuit `&&` / `||` evaluation

Overview

Operators take operands and produce new values. Java's operators look familiar to anyone coming from C/C++, but watch out for **object comparison (`==` vs `.equals()`)** and **integer / floating-point division** — this lecture untangles both.

Core Concepts

1) Arithmetic / comparison / logical

java
int a = 10, b = 3;
System.out.println(a + b);   // 13
System.out.println(a / b);   // 3   (integer division!)
System.out.println(a % b);   // 1
System.out.println(a > b);   // true
System.out.println(a == 10 && b > 0);   // true

2) Increment / decrement

java
int x = 5;
System.out.println(x++);   // 5 (use then increment)
System.out.println(++x);   // 7 (increment then use)

`x++` and `++x` yield different values. Avoid mixing them inside expressions for clarity.

3) Ternary operator

java
int score = 75;
String result = (score >= 60) ? "pass" : "fail";

A short form of `if/else` — handy when you just need a value on one line.

4) `==` vs `.equals()`

java
String a = "hello";
String b = new String("hello");
System.out.println(a == b);         // false  (different reference)
System.out.println(a.equals(b));    // true   (same content)

**Always compare objects (String/Integer/List/...) with `.equals()`**. `==` is for primitives or reference identity.

5) Bitwise operators

java
int mask = 0b1010;
int val  = 0b1100;
System.out.println(mask & val);  // 8   (AND)
System.out.println(mask | val);  // 14  (OR)
System.out.println(mask ^ val);  // 6   (XOR)
System.out.println(mask << 1);   // 20  (left shift)

Useful in flags, hashing, and crypto.

Examples

Example 1 — `Arithmetic.java`: division pitfalls

java
public class Arithmetic {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println(a / b);        // integer division
        System.out.println(a % b);
        System.out.println((double) a / b); // floating-point division
    }
}

**Output**

text
22
12
85
3
2
3.4

**Note:** `int / int` is always an integer. Cast one side to `double` if you need floating-point.

Example 2 — `LogicAndTernary.java`: comparison / logic / ternary

java
public class LogicAndTernary {
    public static void main(String[] args) {
        int score = 75;
        boolean passed = score >= 60;
        System.out.println("passed? " + passed);

        String grade = (score >= 90) ? "A"
                     : (score >= 80) ? "B"
                     : (score >= 70) ? "C"
                     : (score >= 60) ? "D"
                     : "F";
        System.out.println("grade: " + grade);

        boolean ok = score > 0 && score <= 100;
        System.out.println("valid? " + ok);
    }
}

**Output**

text
passed? true
grade: C
valid? true

**Note:** `&&` and `||` are **short-circuit**. That makes `a != null && a.length() > 0` a safe null check.

Example 3 — `EqualsVsEqEq.java`: reference vs content

java
public class EqualsVsEqEq {
    public static void main(String[] args) {
        String a = "Java";
        String b = "Java";
        String c = new String("Java");
        System.out.println("a == b      : " + (a == b));
        System.out.println("a == c      : " + (a == c));
        System.out.println("a.equals(c) : " + a.equals(c));

        Integer x = 100;
        Integer y = 100;
        Integer z = 200;
        Integer w = 200;
        System.out.println("100==100? " + (x == y)); // cached -> true
        System.out.println("200==200? " + (z == w)); // outside cache -> false
        System.out.println("equals    : " + z.equals(w));
    }
}

**Output**

text
a == b      : true
a == c      : false
a.equals(c) : true
100==100? true
200==200? false
equals    : true

**Note:** `Integer` caches `-128 ~ 127`, so `==` may accidentally return true. **Always use `.equals()` for objects.**

Example 4 — `Bitwise.java`: bitwise operators

java
public class Bitwise {
    public static void main(String[] args) {
        int a = 0b1010;
        int b = 0b1100;
        System.out.printf("a & b = %d (%s)%n", a & b, Integer.toBinaryString(a & b));
        System.out.printf("a | b = %d (%s)%n", a | b, Integer.toBinaryString(a | b));
        System.out.printf("a ^ b = %d (%s)%n", a ^ b, Integer.toBinaryString(a ^ b));
        System.out.printf("~a    = %d%n", ~a);
        System.out.printf("a<<1  = %d%n", a << 1);
        System.out.printf("a>>1  = %d%n", a >> 1);
    }
}

**Output**

text
a & b = 8 (1000)
a | b = 14 (1110)
a ^ b = 6 (110)
~a    = -11
a<<1  = 20
a>>1  = 5

**Note:** `~a` equals `-(a+1)` because of two's complement representation.

Full example code (src/)

src/Arithmetic.java

java
public class Arithmetic {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println(a / b);
        System.out.println(a % b);
        System.out.println((double) a / b);
    }
}

src/Bitwise.java

java
public class Bitwise {
    public static void main(String[] args) {
        int a = 0b1010;
        int b = 0b1100;
        System.out.printf("a & b = %d (%s)%n", a & b, Integer.toBinaryString(a & b));
        System.out.printf("a | b = %d (%s)%n", a | b, Integer.toBinaryString(a | b));
        System.out.printf("a ^ b = %d (%s)%n", a ^ b, Integer.toBinaryString(a ^ b));
        System.out.printf("~a    = %d%n", ~a);
        System.out.printf("a<<1  = %d%n", a << 1);
        System.out.printf("a>>1  = %d%n", a >> 1);
    }
}

src/EqualsVsEqEq.java

java
public class EqualsVsEqEq {
    public static void main(String[] args) {
        String a = "Java";
        String b = "Java";
        String c = new String("Java");
        System.out.println("a == b      : " + (a == b));
        System.out.println("a == c      : " + (a == c));
        System.out.println("a.equals(c) : " + a.equals(c));

        Integer x = 100;
        Integer y = 100;
        Integer z = 200;
        Integer w = 200;
        System.out.println("100==100? " + (x == y));
        System.out.println("200==200? " + (z == w));
        System.out.println("equals    : " + z.equals(w));
    }
}

src/LogicAndTernary.java

java
public class LogicAndTernary {
    public static void main(String[] args) {
        int score = 75;
        boolean passed = score >= 60;
        System.out.println("passed? " + passed);

        String grade = (score >= 90) ? "A"
                     : (score >= 80) ? "B"
                     : (score >= 70) ? "C"
                     : (score >= 60) ? "D"
                     : "F";
        System.out.println("grade: " + grade);

        boolean ok = score > 0 && score <= 100;
        System.out.println("valid? " + ok);
    }
}

Common Mistakes

  1. Using `==` for object comparison → switch to `.equals()`
  2. Forgetting `int a = 1/2;` is 0
  3. Mixing postfix `i++` inside an `if` condition and getting confused
  4. Confusing `&&` with `&` (the first short-circuits, the second always evaluates both sides)
  5. An `Integer` cache bug where `==` accidentally works

Summary

  • Be intentional about integer vs floating-point math
  • Object comparison always uses `.equals()`
  • Bitwise operators are useful for flags / hashing / niche cases
  • Short-circuit evaluation is the key tool for null checks

Practice

# Practice - 03. Operators and Expressions

## Exercise 1 — Leap year

  • File: `Homework01.java`
  • Key concepts: comparison / logical operators, short-circuit

Requirements

  • Assign `year = 2024`.
  • Write the leap-year condition (divisible by 4 AND (not divisible by 100 OR divisible by 400)) in one expression.
  • Print `is 2024 a leap year? true`.

Expected output

text
is 2024 a leap year? true

Hint

  • `(year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)`

## Exercise 2 — Grading

  • File: `Homework02.java`
  • Key concepts: nested ternary

Requirements

  • Declare `score = 73`.
  • Use only the ternary operator to decide the letter grade (A/B/C/D/F).
  • Print `score=73 -> grade=C`.

Expected output

text
score=73 -> grade=C

Hint

  • `(score >= 90) ? "A" : (score >= 80) ? "B" : ...`

## Exercise 3 — Even / odd via bits

  • File: `Homework03.java`
  • Key concepts: bitwise AND `&`

Requirements

  • For integers 1..5, use `(n & 1)` to print whether each is even or odd.

Expected output

text
1 -> odd
2 -> even
3 -> odd
4 -> even
5 -> odd

Hint

  • Loops are covered in lecture 04, but a simple `for` is fine here.

## Solutions After trying it yourself, compare with [`answer/`](./answer/).

Solution code (homework/answer/)

answer/Homework01.java

java
/** Leap year. */
public class Homework01 {
    public static void main(String[] args) {
        int year = 2024;
        boolean leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
        System.out.println("is " + year + " a leap year? " + leap);
    }
}

answer/Homework02.java

java
/** Letter grade via ternary. */
public class Homework02 {
    public static void main(String[] args) {
        int score = 73;
        String grade = (score >= 90) ? "A"
                     : (score >= 80) ? "B"
                     : (score >= 70) ? "C"
                     : (score >= 60) ? "D"
                     : "F";
        System.out.println("score=" + score + " -> grade=" + grade);
    }
}

answer/Homework03.java

java
/** Even/odd via bitwise AND. */
public class Homework03 {
    public static void main(String[] args) {
        for (int n = 1; n <= 5; n++) {
            String kind = ((n & 1) == 0) ? "even" : "odd";
            System.out.println(n + " -> " + kind);
        }
    }
}

Try It Yourself

bash
cd 01_basics/03_operators/src
javac Arithmetic.java
java Arithmetic

Next Lecture

[04_Control_Flow](../04_제어문/) — `if` / `switch` / loops.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗