JAVA 1

Phase 1 — Java Foundations

This phase takes you from no strong programming fundamentals to being comfortable reading and writing basic Java programs.

Chapters in this Phase

  1. Java, JDK, JVM & Your First Program

  2. Java Program Structure, Statements & Comments

  3. Variables & Assignment

  4. Primitive Data Types & Literals

  5. Operators & Expressions

  6. Strings & Basic Text Processing

  7. User Input

  8. Type Conversion & Type Casting

  9. Boolean Logic

  10. if, else if & else

  11. switch

  12. for Loops

  13. while & do-while Loops

  14. break, continue & Nested Loops

  15. Methods & return

  16. Method Parameters, Overloading & Varargs

  17. Scope & Lifetime of Variables

  18. Arrays

  19. Multidimensional Arrays

  20. Packages, Imports & Basic Java Organization

  21. Basic Problem-Solving Patterns & Putting Fundamentals Together


Chapter 1 — Java, JDK, JVM & Your First Program

Question

Given below is a code snippet that:

  • Defines a Java class.

  • Defines the main method.

  • Prints text to the console.

  • Demonstrates the basic structure of an executable Java program.

What should be the output of the following code?

// Define a class named Main.
class Main {

    // Java starts running the program from the main method.
    public static void main(String[] args) {

        // Print a message to the console.
        System.out.println("Hello, Java!");

        // Print another message on a new line.
        System.out.println("I am learning Java.");
    }
}

Answer

Hello, Java!
I am learning Java.

Step-by-step explanation

  1. class Main defines a class named Main.

  2. Java needs an entry point to know where execution should begin.

  3. That entry point is main.

  4. System.out.println() prints text.

  5. The first call prints Hello, Java!.

  6. println moves to the next line after printing.

  7. The second call therefore prints I am learning Java. on the next line.

How to read the important code

System.out.println("Hello, Java!");

A programmer naturally says:

"System dot out dot println, passing it the string Hello, Java."

You do not need to say:

"System open parenthesis... semicolon..."

Beginner trap

main is not an ordinary method when you're talking about starting a normal Java application. It is the program's entry point.

Key takeaway

A Java application starts execution from its main method.


Chapter 2 — Java Program Structure, Statements & Comments

Question

Given below is a code snippet that:

  • Uses comments.

  • Demonstrates statements.

  • Uses curly braces to define blocks.

  • Shows that Java executes statements in order.

  • Demonstrates println versus print.

What should be the output of the following code?

// The class contains the program.
class Main {

    // Program execution begins here.
    public static void main(String[] args) {

        // Print without moving to a new line.
        System.out.print("Java ");

        // Print and then move to the next line.
        System.out.println("programming");

        // These two statements execute from top to bottom.
        System.out.print("is ");
        System.out.println("fun!");
    }
}

Answer

Java programming
is fun!

Step-by-step explanation

  1. System.out.print("Java "); prints Java but stays on the same line.

  2. println("programming") prints programming after it.

  3. println then moves to the next line.

  4. print("is ") prints is .

  5. println("fun!") prints fun! and moves to the next line.

Comments beginning with // are ignored by Java when the program runs.

How to read the important code

"Print Java without a newline."

versus:

"Print programming and then move to the next line."

Beginner trap

print() and println() are different.

print()

stays on the current line.

println()

prints and then moves to the next line.

Key takeaway

Java normally executes statements sequentially from top to bottom.


Chapter 3 — Variables & Assignment

Question

Given below is a code snippet that:

  • Declares variables.

  • Assigns initial values.

  • Changes variable values.

  • Uses one variable to calculate another value.

  • Demonstrates assignment with =.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Create an integer variable named price and give it 100.
        int price = 100;

        // Create another integer variable named quantity.
        int quantity = 3;

        // Calculate the total using the current variable values.
        int total = price * quantity;

        // Change the price variable.
        price = 120;

        // Calculate a new total using the new price.
        total = price * quantity;

        // Display the final values.
        System.out.println(price);
        System.out.println(quantity);
        System.out.println(total);
    }
}

Answer

120
3
360

Step-by-step explanation

  1. price starts as 100.

  2. quantity starts as 3.

  3. total becomes 100 × 3, or 300.

  4. price = 120 changes the value stored in price.

  5. total = price * quantity runs again.

  6. Java now calculates 120 × 3.

  7. Therefore total becomes 360.

The = symbol means assignment here.

It means:

"Put this value into this variable."

How to read the important code

int price = 100;

Say:

"Declare an int called price and assign it 100."

price = 120;

Say:

"Assign 120 to price."

Beginner trap

= does not mean "is equal to" in the mathematical sense. It is the assignment operator.

Key takeaway

A variable is a named place for storing a value, and assignment can change that value.


Chapter 4 — Primitive Data Types & Literals

Question

Given below is a code snippet that:

  • Uses several primitive data types.

  • Demonstrates integers, decimals, characters and booleans.

  • Shows that different variables can store different kinds of values.

  • Demonstrates literals.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store a whole number.
        int age = 35;

        // Store a decimal number.
        double salary = 55000.50;

        // Store a single character.
        char grade = 'A';

        // Store either true or false.
        boolean employed = true;

        // Store a smaller whole number.
        long population = 1400000000L;

        // Display all values.
        System.out.println(age);
        System.out.println(salary);
        System.out.println(grade);
        System.out.println(employed);
        System.out.println(population);
    }
}

Answer

35
55000.5
A
true
1400000000

Step-by-step explanation

  1. int stores whole numbers such as 35.

  2. double stores decimal numbers.

  3. char stores one character. Character literals use single quotes: 'A'.

  4. boolean stores true or false.

  5. long stores large whole numbers.

  6. L tells Java that 1400000000 is a long literal.

Some important primitive types are:

TypeTypical use
byteVery small whole numbers
shortSmall whole numbers
intNormal whole numbers
longVery large whole numbers
floatDecimal numbers
doubleDecimal numbers; common default choice
charOne character
booleantrue / false

How to read the important code

"Declare a double called salary and assign it 55000.50."

Beginner trap

String is not a primitive type. It is a Java class. We will deal with it separately.

Key takeaway

Choose a data type according to the kind of value the variable needs to store.


Chapter 5 — Operators & Expressions

Question

Given below is a code snippet that:

  • Uses arithmetic operators.

  • Uses remainder %.

  • Combines several expressions.

  • Demonstrates operator precedence.

  • Uses increment.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store two numbers.
        int a = 10;
        int b = 3;

        // Perform basic arithmetic.
        int sum = a + b;
        int difference = a - b;
        int product = a * b;
        int quotient = a / b;

        // % gives the remainder after division.
        int remainder = a % b;

        // Multiplication happens before addition.
        int result = a + b * 2;

        // Increase a by one.
        a++;

        // Display the results.
        System.out.println(sum);
        System.out.println(difference);
        System.out.println(product);
        System.out.println(quotient);
        System.out.println(remainder);
        System.out.println(result);
        System.out.println(a);
    }
}

Answer

13
7
30
3
1
16
11

Step-by-step explanation

  1. 10 + 3 is 13.

  2. 10 - 3 is 7.

  3. 10 * 3 is 30.

  4. Integer division 10 / 3 gives 3; the decimal part is discarded.

  5. 10 % 3 gives 1, because 1 is the remainder.

  6. a + b * 2 becomes 10 + 6, because multiplication happens before addition.

  7. a++ increases a from 10 to 11.

How to read the important code

a++;

Say:

"Increment a."

or:

"Increase a by one."

Beginner trap

This:

10 / 3

with two int values gives:

3

not:

3.333...

Key takeaway

Operators perform calculations, and Java follows operator precedence when evaluating expressions.


Chapter 6 — Strings & Basic Text Processing

Question

Given below is a code snippet that:

  • Creates strings.

  • Combines strings.

  • Uses string methods.

  • Compares string content correctly.

  • Demonstrates string immutability through reassignment.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Create a user's name.
        String firstName = "Alice";

        // Create another piece of text.
        String lastName = "Smith";

        // Join the two strings.
        String fullName = firstName + " " + lastName;

        // Count the characters.
        int length = fullName.length();

        // Convert the name to uppercase.
        String upperName = fullName.toUpperCase();

        // Check the actual text content.
        boolean same = fullName.equals("Alice Smith");

        // Strings do not change themselves.
        // This creates a new String value and assigns it to fullName.
        fullName = fullName + " Jr.";

        // Display the results.
        System.out.println(fullName);
        System.out.println(length);
        System.out.println(upperName);
        System.out.println(same);
    }
}

Answer

Alice Smith Jr.
11
ALICE SMITH
true

Step-by-step explanation

  1. firstName contains "Alice".

  2. lastName contains "Smith".

  3. + joins strings.

  4. fullName therefore becomes "Alice Smith".

  5. "Alice Smith" contains 11 characters, including the space.

  6. toUpperCase() produces a new string: "ALICE SMITH".

  7. equals() checks whether the actual text is the same.

  8. fullName.equals("Alice Smith") is true.

  9. fullName = fullName + " Jr." creates a new string value and assigns it back to fullName.

How to read the important code

String fullName = firstName + " " + lastName;

Say:

"Create a String called fullName by joining firstName, a space, and lastName."

Beginner trap

Don't normally compare String contents using:

name1 == name2

Use:

name1.equals(name2)

== is about whether two references refer to the same object; equals() is designed to compare String content.

Key takeaway

Strings represent text, and String methods generally produce new String values rather than changing the original String.


Chapter 7 — User Input

Question

Given below is a code snippet that:

  • Creates a Scanner.

  • Reads text from the keyboard.

  • Reads an integer.

  • Uses the input in calculations.

What should be the output if the user enters Alice and then 3?

import java.util.Scanner;

class Main {

    public static void main(String[] args) {

        // Create a Scanner that reads from the keyboard.
        Scanner scanner = new Scanner(System.in);

        // Ask the user for a name.
        System.out.print("Enter your name: ");

        // Read one word from the user.
        String name = scanner.next();

        // Ask the user for a quantity.
        System.out.print("Enter quantity: ");

        // Read an integer from the user.
        int quantity = scanner.nextInt();

        // Calculate the total.
        int total = quantity * 100;

        // Display the result.
        System.out.println("Hello " + name);
        System.out.println("Total: " + total);

        // Close the Scanner.
        scanner.close();
    }
}

Answer

Enter your name: Alice
Enter quantity: 3
Hello Alice
Total: 300

Step-by-step explanation

  1. Scanner allows Java to read input.

  2. System.in represents standard input, normally the keyboard.

  3. next() reads the next word.

  4. nextInt() reads an integer.

  5. The user enters Alice, so name becomes "Alice".

  6. The user enters 3, so quantity becomes 3.

  7. 3 * 100 produces 300.

  8. The program prints the greeting and total.

How to read the important code

Scanner scanner = new Scanner(System.in);

Say:

"Create a Scanner called scanner that reads from standard input."

Beginner trap

next() reads one word. For an entire line containing spaces, you'll commonly use nextLine().

Key takeaway

Scanner is a simple way to read user input from the console.


Chapter 8 — Type Conversion & Type Casting

Question

Given below is a code snippet that:

  • Converts an int to a double.

  • Demonstrates automatic widening conversion.

  • Demonstrates explicit narrowing casting.

  • Shows how integer division differs from decimal division.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store a whole number.
        int number = 10;

        // Java automatically converts int to double here.
        double decimalNumber = number;

        // Convert the decimal value to int explicitly.
        // The decimal portion is discarded.
        int wholeNumber = (int) 12.9;

        // Integer division happens because both operands are ints.
        int integerResult = 5 / 2;

        // Convert one operand to double before division.
        double decimalResult = 5 / 2.0;

        // Display the results.
        System.out.println(decimalNumber);
        System.out.println(wholeNumber);
        System.out.println(integerResult);
        System.out.println(decimalResult);
    }
}

Answer

10.0
12
2
2.5

Step-by-step explanation

  1. number is an int containing 10.

  2. Java can safely put that whole number into a double, so decimalNumber becomes 10.0.

  3. (int) 12.9 explicitly converts the decimal to an integer.

  4. The .9 is discarded, producing 12.

  5. 5 / 2 uses integer division because both values are integers.

  6. Therefore the result is 2.

  7. 5 / 2.0 uses decimal arithmetic because one operand is a double.

  8. Therefore the result is 2.5.

How to read the important code

int wholeNumber = (int) 12.9;

Say:

"Declare an int called wholeNumber and cast 12.9 to int."

Beginner trap

Casting a decimal to an integer does not round normally.

(int) 12.9 → 12
(int) 12.1 → 12

Key takeaway

Type conversion changes a value from one compatible type to another, and casting explicitly tells Java to perform a conversion.


Chapter 9 — Boolean Logic

Question

Given below is a code snippet that:

  • Uses comparison operators.

  • Creates boolean expressions.

  • Uses logical AND.

  • Uses logical OR.

  • Uses logical NOT.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store a user's age and account status.
        int age = 25;
        boolean verified = true;

        // Check whether the user is an adult.
        boolean adult = age >= 18;

        // Both conditions must be true.
        boolean canEnter = age >= 18 && verified;

        // At least one condition must be true.
        boolean specialAccess = age < 18 || verified;

        // ! reverses a boolean value.
        boolean notVerified = !verified;

        // Display the results.
        System.out.println(adult);
        System.out.println(canEnter);
        System.out.println(specialAccess);
        System.out.println(notVerified);
    }
}

Answer

true
true
true
false

Step-by-step explanation

  1. age >= 18 means "is age greater than or equal to 18?"

  2. 25 >= 18 is true.

  3. age >= 18 && verified requires both sides to be true.

  4. Both are true, so canEnter is true.

  5. age < 18 || verified requires at least one side to be true.

  6. age < 18 is false, but verified is true.

  7. Therefore the whole OR expression is true.

  8. !verified reverses true to false.

How to read the important code

age >= 18 && verified

Say:

"Age is greater than or equal to 18 and verified."

Beginner trap

&& means both conditions must be true.

|| means at least one condition must be true.

Key takeaway

Boolean expressions produce true or false and are the foundation of decision-making in programs.


Chapter 10 — if, else if & else

Question

Given below is a code snippet that:

  • Uses conditional execution.

  • Checks multiple conditions.

  • Demonstrates else if.

  • Demonstrates that only the first matching branch executes.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store a student's score.
        int score = 82;

        // Check the score from highest range to lowest range.
        if (score >= 90) {

            // This block runs for scores of 90 or more.
            System.out.println("A");

        } else if (score >= 75) {

            // This block handles scores from 75 through 89.
            System.out.println("B");

        } else if (score >= 60) {

            // This block handles scores from 60 through 74.
            System.out.println("C");

        } else {

            // This handles everything below 60.
            System.out.println("D");
        }
    }
}

Answer

B

Step-by-step explanation

  1. score is 82.

  2. Java checks score >= 90.

  3. 82 >= 90 is false.

  4. Java moves to the else if.

  5. 82 >= 75 is true.

  6. Java prints B.

  7. The remaining branches are skipped.

How to read the important code

"If score is greater than or equal to 90, print A; otherwise, if score is at least 75, print B; otherwise..."

Beginner trap

Once an if/else if branch is successfully executed, Java doesn't continue checking later else if branches.

Key takeaway

Conditional statements allow your program to choose which code should execute based on a condition.


Chapter 11 — switch

Question

Given below is a code snippet that:

  • Uses a switch.

  • Matches a value against cases.

  • Uses break.

  • Demonstrates default.

  • Shows modern arrow-style switch cases.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Store the user's selected menu option.
        int option = 2;

        // Choose an action based on option.
        switch (option) {

            // Case 1 matches option 1.
            case 1 -> System.out.println("Profile");

            // Case 2 matches option 2.
            case 2 -> System.out.println("Orders");

            // Case 3 matches option 3.
            case 3 -> System.out.println("Settings");

            // Run this if no case matches.
            default -> System.out.println("Invalid option");
        }
    }
}

Answer

Orders

Step-by-step explanation

  1. option contains 2.

  2. Java evaluates the switch.

  3. It looks for a case matching 2.

  4. case 2 matches.

  5. Java prints Orders.

  6. The other cases don't execute.

How to read the important code

"Switch on option. If it's 1, print Profile; if it's 2, print Orders; if it's 3, print Settings; otherwise print Invalid option."

Beginner trap

Traditional switch syntax often uses break to prevent fall-through. The arrow-style syntax shown here avoids that particular problem.

Key takeaway

switch is useful when one value needs to be compared against several specific choices.


Chapter 12 — for Loops

Question

Given below is a code snippet that:

  • Uses a for loop.

  • Initializes a counter.

  • Checks a loop condition.

  • Increments the counter.

  • Uses the counter to calculate values.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Repeat the block for numbers 1 through 5.
        for (int i = 1; i <= 5; i++) {

            // Calculate the square of the current number.
            int square = i * i;

            // Display the current number and its square.
            System.out.println(i + " -> " + square);
        }
    }
}

Answer

1 -> 1
2 -> 4
3 -> 9
4 -> 16
5 -> 25

Step-by-step explanation

A for loop has three important parts:

for (initialization; condition; update)
  1. int i = 1 runs once at the beginning.

  2. Java checks i <= 5.

  3. If true, the loop body executes.

  4. square is calculated.

  5. The result is printed.

  6. i++ increases i.

  7. Java checks the condition again.

  8. This continues until i becomes 6.

  9. 6 <= 5 is false, so the loop ends.

How to read the important code

"A for loop: initialize i to one, continue while i is less than or equal to five, and increment i."

Beginner trap

The loop doesn't execute when the condition becomes false. The condition is checked before each iteration.

Key takeaway

A for loop is ideal when you know the basic counting/repetition pattern you need.


Chapter 13 — while & do-while Loops

Question

Given below is a code snippet that:

  • Uses a while loop.

  • Uses a do-while loop.

  • Demonstrates the difference between checking before and after execution.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Start a counter at 1.
        int i = 1;

        // Continue while the condition is true.
        while (i <= 3) {

            // Print the current value.
            System.out.println("while: " + i);

            // Increase the counter.
            i++;
        }

        // Start another counter at 5.
        int j = 5;

        // The do block executes before the condition is checked.
        do {

            // Print the current value.
            System.out.println("do: " + j);

            // Increase the counter.
            j++;

        } while (j < 5);
    }
}

Answer

while: 1
while: 2
while: 3
do: 5

Step-by-step explanation

  1. i starts at 1.

  2. The while condition is checked first.

  3. 1 <= 3 is true, so the body executes.

  4. The loop repeats for 2 and 3.

  5. When i becomes 4, 4 <= 3 is false.

  6. The while loop stops.

  7. j starts at 5.

  8. The do block executes immediately.

  9. It prints do: 5.

  10. j becomes 6.

  11. Java checks 6 < 5, which is false.

  12. The do-while loop stops.

How to read the important code

"Do this block first, then continue while j is less than five."

Beginner trap

A do-while loop always executes its body at least once, even if the condition is initially false.

Key takeaway

while checks before execution; do-while executes once before checking.


Chapter 14 — break, continue & Nested Loops

Question

Given below is a code snippet that:

  • Uses nested loops.

  • Uses continue.

  • Uses break.

  • Demonstrates how these statements affect loop execution.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Outer loop represents rows.
        for (int row = 1; row <= 3; row++) {

            // Inner loop represents columns.
            for (int column = 1; column <= 4; column++) {

                // Skip column 2.
                if (column == 2) {
                    continue;
                }

                // Stop the inner loop when column reaches 4.
                if (column == 4) {
                    break;
                }

                // Print the current position.
                System.out.println(row + "," + column);
            }
        }
    }
}

Answer

1,1
2,1
3,1

Step-by-step explanation

For each row:

  1. column starts at 1.

  2. column == 2 is false.

  3. column == 4 is false.

  4. Java prints the position.

  5. column becomes 2.

  6. continue skips the remaining code in that iteration.

  7. column becomes 3.

  8. Java reaches the print.

  9. Wait—there is an important detail: the code as written would actually print row,3 too.

Therefore, the correct output is:

1,1
1,3
2,1
2,3
3,1
3,3

The break happens when column reaches 4.

How to read the important code

continue;

Say:

"Skip this iteration and move to the next iteration."

break;

Say:

"Break out of this loop."

Beginner trap

continue does not stop the entire loop. It skips the current iteration.

break stops the nearest enclosing loop.

Key takeaway

continue skips an iteration; break exits the current loop.


Chapter 15 — Methods & return

Question

Given below is a code snippet that:

  • Defines methods.

  • Calls methods.

  • Uses parameters.

  • Returns values.

  • Reuses a method multiple times.

What should be the output of the following code?

class Main {

    // This method receives two numbers and returns their sum.
    static int add(int first, int second) {

        // Calculate and return the result.
        return first + second;
    }

    // This method receives a price and quantity and returns the total.
    static int calculateTotal(int price, int quantity) {

        // Multiply the values and return the result.
        return price * quantity;
    }

    public static void main(String[] args) {

        // Call add() and store the returned value.
        int sum = add(10, 20);

        // Call calculateTotal() with different arguments.
        int total = calculateTotal(50, 3);

        // Display both results.
        System.out.println(sum);
        System.out.println(total);
    }
}

Answer

30
150

Step-by-step explanation

  1. add(10, 20) calls the add method.

  2. first receives 10.

  3. second receives 20.

  4. return first + second produces 30.

  5. sum receives that returned value.

  6. calculateTotal(50, 3) is called.

  7. price becomes 50.

  8. quantity becomes 3.

  9. The method returns 150.

  10. total receives 150.

How to read the important code

static int add(int first, int second)

Say:

"Define a static method called add that takes two ints and returns an int."

int sum = add(10, 20);

Say:

"Call add with 10 and 20 and assign the returned value to sum."

Beginner trap

A parameter is the variable defined by the method:

int first

An argument is the actual value supplied when calling it:

add(10, 20)

Key takeaway

Methods package reusable behavior, and return sends a value back to the code that called the method.


Chapter 16 — Method Parameters, Overloading & Varargs

Question

Given below is a code snippet that:

  • Uses method parameters.

  • Demonstrates method overloading.

  • Uses variable-length arguments.

  • Shows Java choosing the appropriate overloaded method.

What should be the output of the following code?

class Main {

    // Method version 1: accepts two integers.
    static int add(int a, int b) {
        return a + b;
    }

    // Method version 2: accepts two doubles.
    static double add(double a, double b) {
        return a + b;
    }

    // Varargs allows zero or more integers.
    static int addAll(int... numbers) {

        // Start the total at zero.
        int total = 0;

        // Visit every supplied number.
        for (int number : numbers) {
            total += number;
        }

        // Return the final total.
        return total;
    }

    public static void main(String[] args) {

        // Java selects the int version.
        System.out.println(add(2, 3));

        // Java selects the double version.
        System.out.println(add(2.5, 3.5));

        // Varargs receives three integers.
        System.out.println(addAll(1, 2, 3, 4));
    }
}

Answer

5
6.0
10

Step-by-step explanation

  1. There are two add methods.

  2. They have the same name but different parameter types.

  3. This is called method overloading.

  4. add(2, 3) matches the integer version.

  5. add(2.5, 3.5) matches the double version.

  6. addAll(1, 2, 3, 4) passes four integers to the varargs parameter.

  7. The enhanced for loop visits each number.

  8. 1 + 2 + 3 + 4 equals 10.

How to read the important code

static int addAll(int... numbers)

Say:

"Define a method called addAll that accepts a variable number of ints."

Beginner trap

Overloading isn't based merely on changing the return type.

This would not be a valid overload:

int add(int a, int b)
double add(int a, int b)

The parameter list needs to differ.

Key takeaway

Overloading lets methods share a name while accepting different parameter lists.


Chapter 17 — Scope & Lifetime of Variables

Question

Given below is a code snippet that:

  • Demonstrates local variables.

  • Demonstrates block scope.

  • Shows that a variable declared inside a block cannot be used outside it.

  • Shows separate variables with the same name in different scopes.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // This variable belongs to the main method's scope.
        int value = 10;

        // Create a separate block.
        {
            // This variable belongs only to this block.
            int inside = 20;

            // Display both accessible variables.
            System.out.println(value);
            System.out.println(inside);
        }

        // The block has ended, so inside no longer exists here.
        // We can still use value because it belongs to the outer scope.
        System.out.println(value);

        // This is a new variable named inside.
        int inside = 30;

        // Display the new variable.
        System.out.println(inside);
    }
}

Answer

10
20
10
30

Step-by-step explanation

  1. value is declared inside main, so it is available throughout its relevant scope.

  2. A new block is created with {}.

  3. inside is declared inside that block.

  4. Both value and inside can be accessed there.

  5. The block ends.

  6. inside from that block is no longer accessible.

  7. value is still accessible.

  8. A new inside variable is then created outside the old block.

  9. That new variable contains 30.

How to read the important code

"Declare a local variable called value."

and:

"Declare inside inside this block."

Beginner trap

A variable's name does not automatically make it available everywhere. Where it is declared determines its scope.

Key takeaway

Scope determines where a variable can be accessed in a program.


Chapter 18 — Arrays

Question

Given below is a code snippet that:

  • Creates an array.

  • Stores multiple values of the same type.

  • Accesses elements by index.

  • Uses length.

  • Traverses the array with an enhanced for loop.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Create an array containing four prices.
        int[] prices = {100, 250, 80, 150};

        // Access the first element.
        System.out.println(prices[0]);

        // Access the third element.
        System.out.println(prices[2]);

        // Arrays have a fixed length.
        System.out.println(prices.length);

        // Visit every element in the array.
        for (int price : prices) {

            // Print the current price.
            System.out.println(price);
        }
    }
}

Answer

100
80
4
100
250
80
150

Step-by-step explanation

  1. prices contains four integers.

  2. Java array indexes start at 0.

  3. prices[0] is 100.

  4. prices[2] is 80.

  5. prices.length is 4.

  6. The enhanced for loop visits each element in order.

  7. Therefore all four prices are printed.

How to read the important code

int[] prices

Say:

"An array of ints called prices."

prices[2]

Say:

"The element at index two in prices."

Beginner trap

The first element is index 0, not index 1.

For four elements:

index:   0    1    2    3
value:  100  250   80  150

Key takeaway

An array stores multiple values of the same type, and indexing starts at zero.


Chapter 19 — Multidimensional Arrays

Question

Given below is a code snippet that:

  • Creates a two-dimensional array.

  • Treats it like rows and columns.

  • Accesses individual elements.

  • Uses nested loops to traverse it.

What should be the output of the following code?

class Main {

    public static void main(String[] args) {

        // Create a 2D array representing two rows of products.
        int[][] sales = {
            {10, 20, 30},
            {40, 50, 60}
        };

        // Access row 0, column 1.
        System.out.println(sales[0][1]);

        // Visit every row.
        for (int row = 0; row < sales.length; row++) {

            // Visit every column in the current row.
            for (int column = 0; column < sales[row].length; column++) {

                // Print the current value.
                System.out.print(sales[row][column] + " ");
            }

            // Move to the next output line after each row.
            System.out.println();
        }
    }
}

Answer

20
10 20 30 
40 50 60 

Step-by-step explanation

  1. sales is a two-dimensional array.

  2. It contains two rows.

  3. Each row contains three values.

  4. sales[0][1] means row 0, column 1.

  5. That value is 20.

  6. The outer loop visits each row.

  7. The inner loop visits each value within that row.

  8. Every value is printed.

How to read the important code

sales[row][column]

Say:

"The value at row and column."

Beginner trap

A two-dimensional Java array is technically an array of arrays. Rows don't have to be the same length, although rectangular arrays are very common.

Key takeaway

Multidimensional arrays allow you to organize arrays into multiple dimensions such as rows and columns.


Chapter 20 — Packages, Imports & Basic Java Organization

Question

Given below is a code snippet that:

  • Uses an imported Java class.

  • Demonstrates a package declaration.

  • Shows how classes can be organized.

  • Uses a class from Java's standard library.

What should be the output of the following code?

// Put this class inside the com.example.shop package.
package com.example.shop;

// Import Java's ArrayList class so we can use its simple name.
import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

        // Create a list of product names.
        ArrayList<String> products = new ArrayList<>();

        // Add products to the list.
        products.add("Laptop");
        products.add("Mouse");

        // Print the number of products.
        System.out.println(products.size());

        // Print the first product.
        System.out.println(products.get(0));
    }
}

Answer

2
Laptop

Step-by-step explanation

  1. package com.example.shop; places the class in a named package.

  2. Packages help organize Java classes and avoid naming conflicts.

  3. import java.util.ArrayList; tells Java we want to use ArrayList by its simple name.

  4. new ArrayList<>() creates the list.

  5. Two products are added.

  6. size() returns the number of elements: 2.

  7. get(0) returns the first element: "Laptop".

How to read the important code

import java.util.ArrayList;

Say:

"Import ArrayList from java dot util."

Beginner trap

import doesn't download or install a library. It mainly allows you to refer to an already available class using its shorter name.

Key takeaway

Packages organize classes, while imports let you conveniently use classes from other packages.


Chapter 21 — Basic Problem-Solving Patterns & Putting Fundamentals Together

Question

Given below is a code snippet that:

  • Uses variables and constants.

  • Reads an array of sales.

  • Uses a loop.

  • Uses conditions.

  • Calls a method.

  • Calculates a total and average.

  • Solves a realistic small programming problem.

What should be the output of the following code?

class Main {

    // Keep the tax rate in one named constant.
    static final double TAX_RATE = 0.10;

    // Calculate the total of all sales.
    static int calculateTotal(int[] sales) {

        // Start the total at zero.
        int total = 0;

        // Visit every sale.
        for (int sale : sales) {

            // Add the current sale to the total.
            total += sale;
        }

        // Return the final total.
        return total;
    }

    public static void main(String[] args) {

        // Store the sales for the day.
        int[] sales = {100, 250, 150, 300};

        // Calculate the total using the method.
        int total = calculateTotal(sales);

        // Calculate the average as a decimal value.
        double average = (double) total / sales.length;

        // Calculate tax using the constant.
        double tax = total * TAX_RATE;

        // Determine whether the sales target was reached.
        boolean targetReached = total >= 700;

        // Display the results.
        System.out.println("Total: " + total);
        System.out.println("Average: " + average);
        System.out.println("Tax: " + tax);
        System.out.println("Target reached: " + targetReached);
    }
}

Answer

Total: 800
Average: 200.0
Tax: 80.0
Target reached: true

Step-by-step explanation

  1. The array contains four sales:

    100, 250, 150, 300

  2. calculateTotal(sales) sends the array to the method.

  3. The enhanced for loop visits every sale.

  4. The total becomes:

    100 + 250 + 150 + 300 = 800

  5. The method returns 800.

  6. sales.length is 4.

  7. (double) total converts 800 to a decimal value before division.

  8. 800 / 4 therefore produces 200.0.

  9. TAX_RATE is 0.10.

  10. 800 × 0.10 produces 80.0.

  11. total >= 700 checks whether 800 is at least 700.

  12. The condition is true.

  13. Therefore targetReached contains true.

How to read the important code

int total = calculateTotal(sales);

Say:

"Call calculateTotal with sales and assign the returned int to total."

for (int sale : sales)

Say:

"For each sale in sales..."

static final double TAX_RATE = 0.10;

Say:

"Declare a static final double constant called TAX_RATE with the value zero point one."

final means the variable cannot be reassigned after initialization.

Beginner trap

This line is important:

double average = (double) total / sales.length;

Without the cast, if both sides were integers, Java would perform integer division.

Key takeaway

Programming is largely about combining simple concepts—data, decisions, repetition, and reusable methods—to solve real problems.


Phase 1 — What You Now Know

You have now covered the complete foundation needed before moving seriously into object-oriented Java.

Java basics

  • Java program structure

  • class

  • main

  • System.out

  • print

  • println

  • Comments

  • Statements

  • Blocks

  • Packages

  • Imports

Data

  • Variables

  • Assignment

  • Primitive types

  • Literals

  • Constants

  • Strings

  • Arrays

  • Multidimensional arrays

Operators

  • Arithmetic

  • Assignment

  • Comparison

  • Logical operators

  • Increment/decrement

  • Remainder

  • Precedence

  • Type conversion

  • Casting

Decision making

  • Boolean expressions

  • if

  • else if

  • else

  • switch

Repetition

  • for

  • Enhanced for

  • while

  • do-while

  • break

  • continue

  • Nested loops

Reusable code

  • Methods

  • Parameters

  • Arguments

  • Return values

  • Overloading

  • Varargs

  • Scope

Practical programming

  • Console input

  • Basic calculations

  • Arrays + loops

  • Conditions + loops

  • Methods + arrays

  • Constants

  • Basic problem-solving patterns


The mental model I want you to develop

At this point, don't think of Java as thousands of syntax rules.

Think:

DATA
 ↓
Variables / Arrays / Strings
 ↓
PROCESSING
 ↓
Operators / Methods
 ↓
DECISIONS
 ↓
if / switch
 ↓
REPETITION
 ↓
for / while
 ↓
ORGANIZATION
 ↓
Methods / Packages
 ↓
SOLVE PROBLEM

That is the foundation on which Phase 2 — Object-Oriented Java + Core Java will be built.

And importantly, Phase 2 will not restart these basics. It will start using them inside increasingly realistic classes, objects, constructors, inheritance, interfaces, polymorphism, encapsulation, exceptions, collections, and generics.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.