Week 1

Environment setup

How Java works

Types and Variables

Arrays

Basic IO

Control Flow

Packages

OOP in Java

Static Members

Practice

Assignment

Back end Track

🎯 Learning Objectives

By the end of this module, you will be able to:


1. if / else if / else

The syntax is nearly identical to JavaScript. The condition inside the parentheses must be a boolean expression — Java has no truthy/falsy values.

int temperature = 22;

if (temperature > 30) {
    System.out.println("It's hot outside.");
} else if (temperature >= 15) {
    System.out.println("Nice weather.");
} else {
    System.out.println("It's cold outside.");
}
// Nice weather.

⚠️ Unlike JavaScript, if (score) or if (name) will not compile. You must write an explicit boolean expression: if (score > 0) or if (name != null).


2. Comparison Operators

These evaluate to true or false and form the conditions in your if statements and loops.

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
< Less than 3 < 7 true
> Greater than 7 > 3 true
<= Less than or equal 5 <= 5 true
>= Greater than or equal 4 >= 6 false

⚠️ Comparing Strings

== on Strings compares memory references, not content. Always use .equals():

String input = "yes";

if (input == "yes") { ... }       // ❌ may not work as expected
if (input.equals("yes")) { ... }  // ✅ always correct

🔍 This is the same concept as === in JavaScript checking reference equality for objects — in Java, == does the same for all reference types.


3. Logical Operators

Use logical operators to combine multiple boolean expressions.

Operator Meaning Example Result
&& AND — both must be true age > 18 && hasID true only if both are true
` ` OR — at least one must be true
! NOT — inverts the boolean !isLoggedIn true if isLoggedIn is false
int age = 20;
boolean hasTicket = true;

if (age >= 18 && hasTicket) {
    System.out.println("Entry granted.");
}

boolean isWeekend = false;
boolean isHoliday = true;

if (isWeekend || isHoliday) {
    System.out.println("Office is closed.");
}

boolean isLoggedIn = false;

if (!isLoggedIn) {
    System.out.println("Please log in first.");
}

Short-circuit Evaluation

Java stops evaluating as soon as the result is determined:

String name = null;

// Safe — if name is null, the right side is never reached
if (name != null && name.equals("Alice")) {
    System.out.println("Hello, Alice!");
}

💡 Short-circuit evaluation is a useful defensive pattern — always put the cheaper or null-safety check on the left side of &&.


4. switch Statement

Use switch when you have one variable with many possible discrete values. It's cleaner than a long chain of else if.

Classic switch

String day = "Wednesday";

switch (day) {
    case "Monday":
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
    case "Friday":
        System.out.println("Weekday");
        break;
    case "Saturday":
    case "Sunday":
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Unknown day");
}

⚠️ The break statement is mandatory in classic switch. Without it, execution falls through into the next case and keeps running until it hits a break or the end of the switch. This is the same behaviour as JavaScript.

Enhanced Switch Expression (Java 14+)

The modern syntax removes fall-through entirely and can return a value directly. No break needed.

String day = "Wednesday";

String type = switch (day) {
    case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "Weekday";
    case "Saturday", "Sunday" -> "Weekend";
    default -> "Unknown day";
};

System.out.println(type); // Weekday

💡 Prefer the enhanced syntax for new code — it's less error-prone and more expressive. The classic syntax still appears frequently in existing codebases, so it's important to recognise both.


5. for Loop

The traditional for loop gives you full control over the counter variable. The structure has three parts: initialise, condition, update.

//        init    condition   update
for (int i = 0; i < 5; i++) {
    System.out.println("Step: " + i);
}
// Step: 0
// Step: 1
// Step: 2
// Step: 3
// Step: 4

The three parts are flexible — you can count down, skip values, or use any step size:

// Count down
for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}

// Step by 2
for (int i = 0; i <= 10; i += 2) {
    System.out.println(i); // 0, 2, 4, 6, 8, 10
}

Use the traditional for loop when:


6. Enhanced for Loop (for-each)

A cleaner, safer way to iterate over arrays and collections when you only need the values, not the index.

String[] languages = {"Java", "Python", "JavaScript"};

for (String language : languages) {
    System.out.println(language);
}
// Java
// Python
// JavaScript

🔍 This is Java's equivalent of for...of in JavaScript. It's the preferred loop when you don't need the index — it's shorter, avoids off-by-one errors, and reads naturally.

You cannot use the enhanced for loop when:


7. while and do-while Loops

while — check first, then run

Use when the loop should only run if the condition is initially true. The number of iterations is not known upfront.

int count = 1;

while (count <= 5) {
    System.out.println("Count: " + count);
    count++;
}

A common real-world use case — keep asking until valid input is received:

Scanner scanner = new Scanner(System.in);
int age = -1;

while (age < 0 || age > 120) {
    System.out.print("Enter a valid age: ");
    age = scanner.nextInt();
}
System.out.println("Age accepted: " + age);

do-while — run first, then check

The body always executes at least once, regardless of the condition. Useful when you need to show a menu or prompt before knowing whether to continue.

Scanner scanner = new Scanner(System.in);
String choice;

do {
    System.out.println("1. Start");
    System.out.println("2. Help");
    System.out.println("3. Quit");
    System.out.print("Choose an option: ");
    choice = scanner.nextLine();
} while (!choice.equals("3"));

System.out.println("Goodbye!");

💡 Rule of thumb: use while when the loop might not need to run at all. Use do-while when it must run at least once — like displaying a menu before reading a choice.


8. break and continue

Both alter the normal flow of a loop.

break — exit the loop immediately