Made for Deniz · A Java refresher

Java Brush-Up

Everything in this guide comes from your own practice repository — the same topics, the same style of exercises, in the same order you learned them. Read each part, then answer the practice questions to wake your memory up.

How to use this guide:

1. Read one part and try the small examples in IntelliJ.

2. Answer the practice questions — write real code, don't just think it.

3. Stuck? Open the Hint. It tells you which tool to use, not the answer.

4. Tick the box when you solve one. Your progress is saved in this browser.

Part 1

Printing to the screen

Every Java program starts inside the main method. To show something on the screen, use System.out.println(...).

Your very first program
public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

println prints and then moves to a new line. print (without "ln") stays on the same line.

println vs print
System.out.println("I love Java");  // goes to a new line after
System.out.print("1 ");
System.out.print("2 ");
System.out.print("3 ");
// output: 1 2 3   (all on one line)

You can join text and numbers with +. Be careful: parentheses change the result!

Joining text and numbers
System.out.println("Total value: " + (5 + 10));  // Total value: 15
System.out.println("Total value: " + 5 + 10);    // Total value: 510  (!)
System.out.println("Result: " + 9 / 3);          // Result: 3  (division runs first)
System.out.println(50 - 15);                     // 35  (no quotes = just math)

Remember: text inside "double quotes" is printed exactly as written. Math without quotes is calculated first. When text comes first, Java glues values to it one by one, from left to right.

Practice time

These are the same kind of questions you solved before. Write each one as a small program.

  1. Hint

    Use System.out.println("...").

  2. Hint

    Same as question 1 — the text goes inside double quotes.

  3. Hint

    Put the math inside println with no quotes around it.

  4. Hint

    Put the addition inside parentheses: "..." + (5 + 10).

  5. Hint

    Division runs before the text join. So what number comes after "Result: "?

  6. Hint

    When text comes first, Java joins left to right: first "Sum: " + 5, then + 10.

  7. Hint

    Use System.out.print — without the "ln".

  8. Hint

    Any text between double quotes works.

  9. Hint

    Each println automatically ends its line.

  10. Hint

    * is the multiplication symbol. No quotes needed.

Part 2

Variables & data types

A variable is a named box that holds a value. You always write: type, name, equals, value.

All the types you used
String learning = "I am learning Java";  // text
int t = 50;                              // whole number
float pi = 3.14f;                        // decimal — needs the letter f
double price = 19.99;                    // decimal — no f needed
boolean isJavaFun = true;                // true or false
char firstLetter = 'J';                  // ONE character, single quotes
long population = 1000000;               // very big whole number

System.out.println(learning);
System.out.println("price = " + price);

You can put the result of math into a variable, then print it with a label.

Store a result, then print it
int x = 5;
int y = 10;
int result = x + y;
System.out.println("Sum result: " + result);   // Sum result: 15

Naming rules

What is allowed
// OK:      myCat   my_name   $money   isAdult   priceOfLipstick
// NOT OK:  2cats   (cannot start with a digit)
// NOT OK:  my-name (dash is not allowed — only _ and $ are)
// Style:   camelCase for names, booleans start with is/has  (isAdult, hasCar)

Remember: float needs an f at the end (3.14f), char uses single quotes 'J', and String uses double quotes "Java".

Practice time

Just like your homework: create the variable, then print it.

  1. Hint

    Type comes first: String learning = "...";

  2. Hint

    int is for whole numbers.

  3. Hint

    booleans hold only true or false, without quotes.

  4. Hint

    A float value must end with f.

  5. Hint

    A char takes exactly one character in single quotes.

  6. Hint

    long is like int, but for very big numbers.

  7. Hint

    Same pattern as question 1.

  8. Hint

    Three variables: x, y, and result = x + y. Then join text + result.

  9. Hint

    Product means multiplication: a * b.

  10. Hint

    Take the old value of x (4) and add 7 to it.

  11. Hint

    A name cannot start with a digit. Only _ and $ are allowed as symbols.

  12. Hint

    double is a decimal type that does not need the f letter.

Part 3

Math operators, % and casting

Java has five math operators: + - * / and %. The last one, modulus, gives the remainder after division — you used it a lot!

The basics
int number = 8;
int square = number * number;           // 64
int cube   = number * number * number;  // 512

int remainder = 23 % 5;                 // 3  (23 / 5 = 4, remainder 3)
System.out.println("23 mod 5 = " + remainder);

Order matters. Multiplication and division run before plus and minus. Parentheses always win.

Precedence
int m = 5 + 20 * 2;    // 45  (20*2 first)
int n = (5 + 20) * 2;  // 50  (parentheses first)

int half = 7 / 2;      // 3, NOT 3.5 — int division throws away the decimals!
Four ways to add 1
counter = counter + 1;
counter += 1;
counter++;
++counter;   // all four do the same thing here

Casting changes one type into another. Going from decimal to int loses the decimal part.

Casting
float price = 12.99f;
int intPrice = (int) price;        // 12 — decimals are cut off, not rounded

double average = (double) 7 / 2;   // 3.5 — cast first, then divide
A classic trick: digits of a number
int n = 47;
int tens = n / 10;   // 4
int ones = n % 10;   // 7

Remember: x % 2 == 0 means x is even. a % b == 0 means a is exactly divisible by b. int divided by int is always an int.

Practice time

Mix of coding tasks and "trace it in your head" puzzles — just like the CihanOrnek drills.

  1. Hint

    Square = the number times itself.

  2. Hint

    Cube = number * number * number.

  3. Hint

    (number * 3 + 5)

  4. Hint

    Parentheses first: ((a + b) * 3 + 8).

  5. Hint

    Use the % operator.

  6. Hint

    7 × 6 = 42. What is left over?

  7. Hint

    4 × 4 = 16. What remains?

  8. Hint

    Do it step by step: 3 → 8 → ... → ?

  9. Hint

    Both numbers are ints, so the result is an int.

  10. Hint

    (5 / 2) is int division — the decimals disappear before the multiply.

  11. Hint

    n / 10 and n % 10.

  12. Hint

    Long form, +=, and the two ++ forms.

  13. Hint

    Casting to int cuts off the decimals. It does not round.

  14. Hint

    Cast one side: (double) sum / count.

  15. Hint

    Multiplication before addition — unless parentheses say otherwise.

Part 4

User input with Scanner

Scanner lets your program ask the user for a value. First import it, then create it, then read.

Reading a number
import java.util.Scanner;

Scanner kb = new Scanner(System.in);
System.out.print("Please enter a number: ");
int number = kb.nextInt();
System.out.println("You entered: " + number);
Reading text and decimals
String name = kb.nextLine();     // reads a whole line of text
double radius = kb.nextDouble(); // reads a decimal number

double area = 3.14159 * radius * radius;
System.out.println("Circle area: " + area);

Remember: nextInt() for whole numbers, nextDouble() for decimals, nextLine() for text. Always print a friendly message before reading, so the user knows what to type.

Practice time

Run each one and type real values in the console.

  1. Hint

    Call kb.nextInt() twice, into two variables.

  2. Hint

    nextLine() reads text. Join with +.

  3. Hint

    Use double and nextDouble(). Area = pi * r * r.

  4. Hint

    Two nextInt() calls, then multiply.

  5. Hint

    Read into a variable, then print text + variable.

  6. Hint

    int division loses decimals — cast the sum with (double).

  7. Hint

    A comparison like age > 18 IS a boolean value — assign it directly.

  8. Hint

    Digits again: n / 10 and n % 10, then add them.

  9. Hint

    Read an int, print with a label.

  10. Hint

    One reads a whole number, the other reads a whole line of text.

Part 5

If / else / else-if

An if lets your program make decisions. You compare values with > < >= <= == and !=.

if alone, and if/else
int shoePrice = 20;
if (shoePrice < 25) {
    System.out.println("I can buy these shoes for sport");
}

int mealCalories = 700;
if (mealCalories > 600) {
    System.out.println("This meal is very high-calorie!");
} else {
    System.out.println("This meal is healthy");
}

For more than two roads, chain conditions with else if. Java checks them from top to bottom and runs only the first one that matches.

else-if ladder
int hourOfDay = 14;
if (hourOfDay < 6) {
    System.out.println("Night time");
} else if (hourOfDay < 18) {
    System.out.println("Daytime");
} else {
    System.out.println("Evening time");
}

Chars are compared with == too. And a very useful pattern from your exercises: set a variable inside the branches, print once at the end.

char comparison + assign-in-branch pattern
char grade = 'A';
if (grade == 'A') {
    System.out.println("Excellent");
} else if (grade == 'B') {
    System.out.println("Good");
} else {
    System.out.println("Invalid grade!");
}

int age = 10;
int ticketPrice;
if (age < 12) {
    ticketPrice = 10;
} else {
    ticketPrice = 20;
}
System.out.println("Ticket price: " + ticketPrice);

Remember: one = assigns a value, two == compares. In an else-if ladder you don't need to repeat the lower bound — if the code reached else if (age < 12), age is already 4 or more.

Practice time

These come straight from your if/else homework set.

  1. Hint

    A single if is enough — no else needed.

  2. Hint

    Use the > operator.

  3. Hint

    Three roads: > 0, == 0, else.

  4. Hint

    Classic if/else, two roads.

  5. Hint

    Same shape as question 4.

  6. Hint

    An else-if ladder with three roads.

  7. Hint

    Check the smallest range first, then let else-if handle the rest.

  8. Hint

    Three-road ladder again.

  9. Hint

    Same ladder pattern — pick your boundaries carefully.

  10. Hint

    Four roads: if, two else-ifs, and a final else.

  11. Hint

    Compare chars with == and single quotes: grade == 'A'.

  12. Hint

    Make String message = ""; first, fill it in the branches.

  13. Hint

    Assign inside the branches; only one println at the bottom.

  14. Hint

    Ladder from the top: check >= 90 first, then you don't need upper bounds.

  15. Hint

    Because else-if runs in order, humanAge < 12 already means "4 or more".

Part 6

Logical operators: &&, ||, !

Sometimes one condition is not enough. && means AND (both must be true), || means OR (at least one is true), ! means NOT.

Combining conditions
int number = 30;
if (number % 3 == 0 && number % 5 == 0) {
    System.out.println("divisible by both 3 and 5");
}

if (number % 2 == 0 && number % 4 != 0) {
    System.out.println("divisible by 2 but not by 4");   // true for 6, 14, 30...
}

A comparison is a boolean value. You can store it in a variable with a nice name.

Named booleans
int x = 8;
boolean isEven = (x % 2) == 0;        // "is it even?" → true

int age = 70;
boolean isEligibleForRetirement = age > 65;
System.out.println(isEligibleForRetirement);   // true
Two variables in one condition
int temperature = 33;
int humidity = 75;
if (temperature > 30 && humidity > 70) {
    System.out.println("The weather is stifling");
} else if (temperature < 15 && humidity < 30) {
    System.out.println("The weather is dry and cool");
}

Remember: % + logical operators is a power combo: even = % 2 == 0, odd = % 2 != 0, "divisible by a but not b" = % a == 0 && % b != 0.

Practice time

The mod + logic drills — your favourite question folder.

  1. Hint

    number % 2 == 0

  2. Hint

    Multiple of 3 means remainder 0 when divided by 3.

  3. Hint

    Two % checks joined with &&.

  4. Hint

    Use != for the "not" part: % 4 != 0.

  5. Hint

    Odd = % 2 == 1. Join with &&.

  6. Hint

    Two conditions per branch, joined with &&.

  7. Hint

    Same two-variable pattern as question 6.

  8. Hint

    Two conditions joined with && in each branch — you solved this one with funny messages.

  9. Hint

    No if needed at all — assign the comparison directly.

  10. Hint

    boolean isEligibleForRetirement = age > 65;

Part 7

While loops

A while loop repeats code as long as a condition is true. You need three things: a counter, a condition, and a step that changes the counter — or the loop never ends!

The classic shape
int i = 0;
while (i < 5) {
    System.out.println("*");
    i++;                      // never forget this line!
}
Doubling: 1, 2, 4, 8, 16
int number = 1;
int i = 1;
while (i <= 5) {
    System.out.println(number);
    number = number * 2;
    i++;
}
while(true) + break
int i = 0;
while (true) {                // runs forever...
    System.out.println("Hello");
    i++;
    if (i == 5) {
        break;                // ...until break stops it
    }
}

Remember: if you forget i++, the condition never becomes false and the loop runs forever. This was the bug in one of the repo files — the loop body only counted and never printed!

Practice time

Solve each one with a while loop, even if a for loop feels easier.

  1. Hint

    Counter starts at 0, condition i < 5, and i++ inside.

  2. Hint

    Same shape, different condition number.

  3. Hint

    Start the counter at 1 and print the counter itself.

  4. Hint

    Scanner first, then while (i <= n).

  5. Hint

    Two variables: the number (× 2 each round) and a counter.

  6. Hint

    Start at 20 and subtract 2 each round: i -= 2.

  7. Hint

    Condition i >= 1, step i--.

  8. Hint

    Put an if (i % 3 == 0) inside the loop.

  9. Hint

    if/else inside the loop, with % 2.

  10. Hint

    Print i * i instead of i.

  11. Hint

    Count inside, and break when the counter hits 5.

  12. Hint

    Make int total = 0; before the loop and do total += i; inside.

Part 8

For loops

A for loop puts the counter, the condition, and the step all on one line. Best choice when you know how many times to repeat.

The shape: start; condition; step
for (int i = 1; i <= 5; i++) {
    System.out.println(i);        // 1 2 3 4 5
}

for (int i = 20; i >= 2; i -= 2) {
    System.out.println(i);        // 20 18 16 ... 2
}

for (int i = 1; i <= 16; i = i * 2) {
    System.out.println(i);        // 1 2 4 8 16
}

The accumulator pattern: build up a total inside the loop.

Summing with an accumulator
int total = 0;
for (int i = 1; i <= 5; i++) {
    total += i;
}
System.out.println("Total = " + total);   // 15
FizzBuzz — the famous one
for (int i = 1; i <= 30; i++) {
    if (i % 3 == 0) {
        System.out.println("Fizz");
    } else if (i % 5 == 0) {
        System.out.println("Buzz");
    } else {
        System.out.println(i);
    }
}

Remember: the step doesn't have to be i++ — it can be i--, i -= 2, even i = i * 2. And an if inside a loop is how you filter numbers.

Practice time

The biggest topic in your repo — so the biggest quiz.

  1. Hint

    for (int i = 1; i <= 5; i++)

  2. Hint

    The loop body doesn't have to use i.

  3. Hint

    Either filter with % 2 == 0, or start at 2 and step by 2.

  4. Hint

    Accumulator + an if filter inside the loop.

  5. Hint

    if / else if / else inside the loop. Order matters!

  6. Hint

    Odd = % 2 != 0.

  7. Hint

    Use System.out.print(i + " ") and an if.

  8. Hint

    Two % checks joined with &&.

  9. Hint

    An else-if ladder inside the loop.

  10. Hint

    This one wants ||, not &&.

  11. Hint

    Print only when i % 4 != 0.

  12. Hint

    Divisible by 2 and 5 is the same as divisible by 10.

  13. Hint

    if → print the message, else → print the number.

  14. Hint

    Descending loop + % 2 != 0 check.

  15. Hint

    The step can be i = i * 2.

Part 9

Strings & string methods

A String has built-in methods — small tools you call with a dot. These are the ones you practiced:

The toolbox
String name = "Thailand";
name.length();          // 8  — how many characters
name.charAt(0);         // 'T' — character at a position (starts at 0!)
name.toUpperCase();     // "THAILAND"
name.toLowerCase();     // "thailand"
name.contains("ai");    // true
name.startsWith("T");   // true
name.endsWith("d");     // true
name.indexOf("a");      // 2  — position of the first 'a'
name.replace('a', '*'); // "Th*il*nd"
name.substring(0, 4);   // "Thai" — from 0 up to (not including) 4

Comparing text: use .equals(), never ==. For "ignore big/small letters" use .equalsIgnoreCase().

equals vs equalsIgnoreCase
String name1 = "HasoMis";
String name2 = "HAsOmiS";
name1.equals(name2);            // false — case matters
name1.equalsIgnoreCase(name2);  // true
Classic exercise: cut an email into pieces
String email = "denizukad@gmail.com";
int atIndex = email.indexOf("@");
String username = email.substring(0, atIndex);   // "denizukad"
String website  = email.substring(atIndex + 1);  // "gmail.com"
Walk through a string, one char at a time
String word = "Java";
for (int i = 0; i < word.length(); i++) {
    System.out.println(word.charAt(i));
}

Remember: positions start at 0. The last character is at length() - 1. In substring(start, end) the start is included, the end is not.

Practice time

Ask the user for the text with Scanner, like the original exercises did.

  1. Hint

    .length()

  2. Hint

    .charAt(0) and .charAt(city.length() - 1)

  3. Hint

    .toUpperCase()

  4. Hint

    .equalsIgnoreCase()

  5. Hint

    .contains("@")

  6. Hint

    .replace('a', '*')

  7. Hint

    .substring(1, s.length() - 1)

  8. Hint

    .startsWith("S") gives a boolean directly.

  9. Hint

    A for loop from 0 to length, with .charAt(i).

  10. Hint

    Find "@" with .indexOf, then .substring(0, thatIndex).

  11. Hint

    You need two indexOf results — one for "@", one for ".".

  12. Hint

    .substring(0, 3)

  13. Hint

    .substring(word.length() - 2) — one argument goes to the end.

  14. Hint

    .substring(0, word.length() - 1)

  15. Hint

    word.substring(0, 2) + word

Part 10

Arrays

An array holds many values of the same type in one variable. Each value has a position (index) starting at 0.

Create, read, loop
String[] colours = {"Red", "Blue", "Green", "Yellow"};
System.out.println(colours[0]);        // Red — first element

for (int i = 0; i < colours.length; i++) {
    System.out.println(colours[i]);
}
Filtering with an if inside the loop
int[] numbers = {5, 12, 9, 21, 17, 6};
for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 == 0) {
        System.out.println(numbers[i]);   // only 12 and 6
    }
}
Backwards, and adding up
int[] evens = {2, 4, 6, 8, 10, 12};
for (int i = evens.length - 1; i >= 0; i--) {
    System.out.println(evens[i]);         // 12 10 8 ...
}

int[] weights = {60, 63, 64, 59, 55, 52};
int total = 0;
for (int i = 0; i < weights.length; i++) {
    total += weights[i];
}
An empty array you fill yourself
int[] a = new int[5];          // 5 empty slots, all 0
for (int i = 0; i < a.length; i++) {
    a[i] = (i + 1) * 2;        // fills with 2, 4, 6, 8, 10
}

Remember: for arrays it is .length with no parentheses (Strings use .length() with parentheses). The last index is length - 1.

Practice time

Create the array yourself, then loop over it.

  1. Hint

    {"Red", "Blue", ...} then loop to .length.

  2. Hint

    Just list them in the curly braces.

  3. Hint

    chars use single quotes: {'A', 'B', ...}

  4. Hint

    Same pattern as question 1.

  5. Hint

    Five chars in braces, then a loop.

  6. Hint

    An if inside the loop: numbers[i] > 5.

  7. Hint

    numbers[i] % 2 == 0

  8. Hint

    Each element is a String, so it has .length().

  9. Hint

    Character.isUpperCase(letters[i])

  10. Hint

    Start the loop at length - 1 and go down with i--.

  11. Hint

    Accumulator + % 2 != 0 filter.

  12. Hint

    .endsWith("r")

  13. Hint

    % 3 == 0 && % 9 != 0

  14. Hint

    A number ends in 0 when % 10 == 0.

  15. Hint

    Fill with a[i] = (i + 1) * 2;. For a decimal average, remember the (double) cast.

Part 11

ArrayList

An ArrayList is like an array that can grow. You add items one by one. For numbers and chars you use the "big" type names: Integer, Double, Character.

Create, add, read
import java.util.ArrayList;

ArrayList<String> cities = new ArrayList<>();
cities.add("Istanbul");
cities.add("Bangkok");
cities.add("Chiang Mai");

cities.size();      // 3   (not .length!)
cities.get(0);      // "Istanbul"
System.out.println(cities);   // [Istanbul, Bangkok, Chiang Mai]
Three ways to loop
// 1. index loop
for (int i = 0; i < cities.size(); i++) {
    System.out.println(cities.get(i));
}

// 2. for-each — the easy one
for (String city : cities) {
    System.out.println(city);
}

// 3. forEach with a lambda
cities.forEach(city -> {
    System.out.println(city);
});
Filtering, Thailand style
ArrayList<Integer> days = new ArrayList<>();
days.add(3); days.add(7); days.add(10); days.add(15); days.add(22);

for (int day : days) {
    if (day > 10) {
        System.out.println("day = " + day);   // 15 and 22
    }
}

Remember: array → .length, String → .length(), ArrayList → .size(). Three different spellings — a classic exam trap!

Practice time

The Thailand questions — your repo's favourite theme.

  1. Hint

    new ArrayList<>() then .add(...) for each.

  2. Hint

    For int values the list type is Integer.

  3. Hint

    for (String day : days)

  4. Hint

    Same as question 3.

  5. Hint

    Decimals → Double.

  6. Hint

    for-each + if.

  7. Hint

    Compare Strings with .equals(...), join with ||.

  8. Hint

    % 2 == 1

  9. Hint

    city.length() > 7

  10. Hint

    Index loop from size() - 1 down to 0, with .get(i).

  11. Hint

    Accumulator variable + % 2 == 0 filter.

  12. Hint

    list.forEach(item -> { ... });

Part 12

Set & HashMap

A Set is a collection with no duplicates — if you add the same thing twice, it keeps only one.

Set removes duplicates by itself
import java.util.Set;
import java.util.HashSet;

Set<String> cityNames = new HashSet<>();
cityNames.add("Bangkok");
cityNames.add("Bangkok");     // ignored — already there
cityNames.add("Phuket");

for (String city : cityNames) {
    System.out.println(city);  // Bangkok appears only once
}

A HashMap stores pairs: a key and its value. You look values up by key.

put, get, and looping
import java.util.HashMap;

HashMap<String, String> names = new HashMap<>();
names.put("Deniz", "Turkey");
names.put("Somchai", "Thailand");

names.get("Deniz");            // "Turkey"

for (String key : names.keySet()) {
    String value = names.get(key);
    System.out.println(key + " lives in " + value);
}

// or with a lambda:
names.forEach((key, value) -> {
    System.out.println(key + " -> " + value);
});

Remember: List = keeps order, allows duplicates. Set = no duplicates. Map = key → value pairs. put to add, get to read, keySet() to loop.

Practice time

Short section, short quiz.

  1. Hint

    A Set silently drops the second "Bangkok".

  2. Hint

    The list keeps the duplicates, the set does not.

  3. Hint

    for-each over the set, .equals() and ||.

  4. Hint

    .contains("t")

  5. Hint

    student.get("name")

  6. Hint

    System.out.println(map) prints all pairs.

  7. Hint

    get returns just the value for that key.

  8. Hint

    for (String key : map.keySet()) then map.get(key).

  9. Hint

    Join key + text + value inside the loop.

  10. Hint

    map.forEach((key, value) -> { ... });

Part 13

Methods (functions)

A method is a named block of code you can reuse. Instead of copying the same lines again and again, you write them once and call the name.

The template
public static returnType methodName(parameters) { ... }

// simplest: no parameters, returns nothing (void)
public static void printWelcome() {
    System.out.println("Welcome to Java programming!");
}

// with parameters
public static void printDifference(int a, int b) {
    System.out.println("Difference: " + (a - b));
}

public static void main(String[] args) {
    printWelcome();
    printDifference(10, 4);   // Difference: 6
}

A method can also return a value. Then void becomes the value's type, and the method ends with return.

Returning values
public static int multiply(int a, int b) {
    return a * b;
}

public static String checkEvenOdd(int number) {
    if (number % 2 == 0) {
        return "Even";
    } else {
        return "Odd";
    }
}

int result = multiply(4, 3);            // 12
System.out.println(checkEvenOdd(9));    // Odd
Building a result with a loop
public static String repeatLaugh(int times) {
    String result = "";
    for (int i = 0; i < times; i++) {
        result += "ha";
    }
    return result;
}
// repeatLaugh(3) → "hahaha"

The best trick from the Catan exercises: one method's return value becomes another method's parameter.

Chaining methods (Catan style)
public static int calculateKnightPoints(int knightCards) {
    return knightCards;      // each knight = 1 point
}
public static void printKnightPoints(int points) {
    System.out.println("Knight points: " + points);
}

printKnightPoints(calculateKnightPoints(5));   // Knight points: 5

Remember: void = prints or does something, returns nothing. A return type (int, String...) = gives a value back that you can store or pass on. After return, the method stops.

Practice time

Sweden and Catan questions included — of course.

  1. Hint

    public static void, empty parentheses.

  2. Hint

    One int parameter, join text + parameter.

  3. Hint

    Two parameters, separated by a comma.

  4. Hint

    if/else inside the method — and be careful not to call the method from inside itself!

  5. Hint

    A String parameter this time.

  6. Hint

    if / else if / else — three roads.

  7. Hint

    A for loop inside the method, using n as the limit.

  8. Hint

    Return type is int, not void.

  9. Hint

    return a * b;

  10. Hint

    Return type String; a return in each branch.

  11. Hint

    Start with an empty String and add "ha" in a loop.

  12. Hint

    Accumulator inside, return sum; at the end.

  13. Hint

    settlements * 1 + cities * 2

  14. Hint

    The answer is the smaller of the two values.

  15. Hint

    printKnightPoints(calculateKnightPoints(5));

Part 14

Classes & objects

A class is a blueprint. It says what data (fields) something has. From one class you can create many objects with new.

A class and its objects
public class Phone {
    String brand;
    String model;
    int storage;
}

// in main:                 ClassName variableName = new ClassName()
Phone phone1 = new Phone();
phone1.brand = "iphone";
phone1.model = "iphone 13";
phone1.storage = 36;

Phone phone2 = new Phone();
phone2.brand = "samsung";

A constructor lets you fill the fields in one line. Inside it, this.name means "the field of this object".

Constructor + this
public class Employee {
    String name;
    String position;
    int salary;

    public Employee(String name, String position, int salary) {
        this.name = name;
        this.position = position;
        this.salary = salary;
    }
}

Employee employee1 = new Employee("Deniz", "QA", 85000);

To print an object nicely, add a toString() method — then println(object) just works. (IntelliJ can generate it for you.)

toString
@Override
public String toString() {
    return "Employee{name='" + name + "', position='" + position +
           "', salary=" + salary + "}";
}

System.out.println(employee1);
// Employee{name='Deniz', position='QA', salary=85000}

Objects can live inside lists, and everything you learned before still works:

Objects in an ArrayList
List<Country> countries = new ArrayList<>();
countries.add(hungary);
countries.add(vietnam);

for (Country country : countries) {
    if (country.population > 50000) {
        System.out.println(country.capitalCity);
    }
}

Remember: class = the blueprint, object = one real thing made from it. new creates the object. A class can have more than one constructor (with different parameters) — that is called overloading.

Practice time

The 15 class questions in your repo all follow this pattern: make the class, create 3 objects, print them.

  1. Hint

    No constructor needed — use phone1.brand = "...".

  2. Hint

    The helper is static void and takes the whole object as its parameter.

  3. Hint

    With toString, System.out.println(book1) is enough.

  4. Hint

    The constructor fills all fields in one line — no field assignments needed.

  5. Hint

    Exactly the pattern from the example above.

  6. Hint

    Remember: float fields take values like 8.5f.

  7. Hint

    Same recipe: constructor, toString, three objects.

  8. Hint

    All three fields can be simple types: String, int, int.

  9. Hint

    Two constructors with different parameter lists — this is overloading.

  10. Hint

    The parameter and the field often have the same name — this.name picks the field.

  11. Hint

    for-each over the list, then country.population > 50000.

  12. Hint

    Mix of the two styles: set fields by hand, print with println(object).