Java for Beginners, Lesson 30: Revision and Mini-Programs in Java

Java for Beginners · Module 6: Objects and Revision


🎉 You Have Reached the Last Lesson

You started by asking “What is Java?” and you now know the building blocks of the language. This final lesson does two things: it gives you a revision map of the whole series, and four mini-programs that combine many lessons at once. The best way to learn programming is to type these programs yourself, change them, and break them.

ModuleLessonsYou can now…
1. Getting Started1 – 5explain Java, install the JDK, write and run Hello World
2. Building Blocks6 – 11use variables, types, casting, input and scope
3. Operators12 – 15write any expression and know the order it is evaluated in
4. Control Flow16 – 20make decisions and repeat work with loops
5. Data and Methods21 – 28use arrays, Strings, methods, recursion, ArrayList and exceptions
6. Objects and Revision29 – 30create classes and objects, and combine everything

Figure 1: The six modules of the series.

1️⃣ Revision Map

Module 1: Getting Started

Module 2: Building Blocks

Module 3: Operators

Module 4: Control Flow

Module 5: Data and Methods

Module 6: Objects and Revision

One-page cheat sheet

TopicRemember
Typesint, long, double, char, boolean, byte, short, float. String is a class.
CastingWidening is automatic. Narrowing needs (type). int / int drops the fraction.
Operators% remainder, && / || short-circuit, == versus =, use brackets when unsure.
Decisionsif / else if / else, switch on int, char, String. Always use braces.
Loopsfor when the count is known, while when it is not, do-while for at least once.
ArraysIndex 0 to length – 1. a.length. Arrays.toString. Copy with clone().
StringsImmutable. Compare with equals(). Use StringBuilder in loops.
MethodsReturn type, parameters, pass by value, overloading.
RecursionBase case plus a smaller recursive case.
ArrayListResizable, holds wrappers: ArrayList<Integer>.
Exceptionstry / catch / finally. Specific catches first.
OOPClass = blueprint, object = instance, constructor, this, private + getters.

2️⃣ Mini-Program 1: Marks Report

Combines Scanner (10), arrays (21), loops (19), methods (25), casting (9) and the else-if ladder (16).

import java.util.Scanner;

public class MarksReport {
    static char grade(double pct) {
        if (pct >= 90) return 'A';
        else if (pct >= 75) return 'B';
        else if (pct >= 60) return 'C';
        else if (pct >= 40) return 'D';
        return 'F';
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("How many subjects? ");
        int n = sc.nextInt();
        int[] marks = new int[n];
        int total = 0, best = 0;
        for (int i = 0; i < n; i++) {
            System.out.print("Marks for subject " + (i + 1) + ": ");
            marks[i] = sc.nextInt();
            total += marks[i];
            if (marks[i] > marks[best]) best = i;
        }
        double pct = (double) total / n;
        System.out.println("Total      = " + total + " / " + (n * 100));
        System.out.printf("Percentage = %.2f%%%n", pct);
        System.out.println("Best       = subject " + (best + 1) + " (" + marks[best] + ")");
        System.out.println("Grade      = " + grade(pct));
    }
}
🖥️ Output (bold = what the user types):
How many subjects? 4
Marks for subject 1: 88
Marks for subject 2: 92
Marks for subject 3: 76
Marks for subject 4: 95
Total = 351 / 400
Percentage = 87.75%
Best = subject 4 (95)
Grade = B
  • The array is sized from the user’s answer, so it fits any number of subjects.
  • best stores the index of the highest mark, and the loop updates it whenever a higher mark appears.
  • The cast (double) total keeps the fraction in the percentage. %% prints a percent sign, and %n is a line break.

3️⃣ Mini-Program 2: ATM Menu

Combines do-while (18), the modern switch (17), if (16) and decimal arithmetic.

import java.util.Scanner;

public class AtmMenu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double balance = 5000;
        int choice;
        do {
            System.out.println("\n1. Balance  2. Deposit  3. Withdraw  0. Exit");
            System.out.print("Choice: ");
            choice = sc.nextInt();
            switch (choice) {
                case 1 -> System.out.println("Balance: " + balance);
                case 2 -> {
                    System.out.print("Amount: ");
                    double amt = sc.nextDouble();
                    if (amt > 0) {
                        balance += amt;
                        System.out.println("Deposited. New balance: " + balance);
                    } else {
                        System.out.println("Invalid amount");
                    }
                }
                case 3 -> {
                    System.out.print("Amount: ");
                    double amt = sc.nextDouble();
                    if (amt > 0 && amt <= balance) {
                        balance -= amt;
                        System.out.println("Please collect cash. New balance: " + balance);
                    } else {
                        System.out.println("Insufficient balance or invalid amount");
                    }
                }
                case 0 -> System.out.println("Thank you!");
                default -> System.out.println("Invalid choice");
            }
        } while (choice != 0);
    }
}
🖥️ Output (bold = what the user types):

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 1
Balance: 5000.0

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 2
Amount: 1500
Deposited. New balance: 6500.0

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 3
Amount: 9000
Insufficient balance or invalid amount

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 3
Amount: 2000
Please collect cash. New balance: 4500.0

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 7
Invalid choice

1. Balance 2. Deposit 3. Withdraw 0. Exit
Choice: 0
Thank you!
  • do-while shows the menu at least once, and repeats until the user chooses 0.
  • Each case with several statements uses braces. The two inner amt variables are fine, because each lives in its own block (Lesson 11).
  • Money in real banking software uses BigDecimal, as noted in Lesson 8. A double is fine for learning.

4️⃣ Mini-Program 3: Text Tools

Combines Strings (23, 24), methods (25), for-each (19) and StringBuilder.

public class TextTools {
    static boolean isPalindrome(String s) {
        String clean = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        String rev = new StringBuilder(clean).reverse().toString();
        return clean.equals(rev);
    }

    static int countVowels(String s) {
        int count = 0;
        for (char c : s.toLowerCase().toCharArray()) {
            if ("aeiou".indexOf(c) >= 0) count++;
        }
        return count;
    }

    static String capitalizeWords(String s) {
        StringBuilder sb = new StringBuilder();
        for (String w : s.trim().split("\\s+")) {
            sb.append(Character.toUpperCase(w.charAt(0))).append(w.substring(1).toLowerCase()).append(" ");
        }
        return sb.toString().trim();
    }

    public static void main(String[] args) {
        String[] tests = {"Madam", "A man, a plan, a canal: Panama", "Java"};
        for (String t : tests) {
            System.out.println("\"" + t + "\" palindrome? " + isPalindrome(t));
        }
        System.out.println("vowels in 'Object Oriented Programming' = " + countVowels("Object Oriented Programming"));
        System.out.println(capitalizeWords("  welcome   to jAVA for beginners "));
    }
}
🖥️ Output:
“Madam” palindrome? true
“A man, a plan, a canal: Panama” palindrome? true
“Java” palindrome? false
vowels in ‘Object Oriented Programming’ = 9
Welcome To Java For Beginners
  • replaceAll("[^a-z0-9]", "") removes everything that is not a letter or digit, using a pattern (a regular expression). That is why the sentence with commas and spaces still counts as a palindrome.
  • StringBuilder.reverse() reverses the cleaned text.
  • capitalizeWords splits on runs of spaces, upper-cases the first letter of each word, lower-cases the rest and joins them back.

5️⃣ Mini-Program 4: Number Tools

Combines methods (25), recursion (26), ArrayList (27), loops (19) and a pattern.

import java.util.ArrayList;

public class NumberTools {
    static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int d = 2; d * d <= n; d++) {
            if (n % d == 0) return false;
        }
        return true;
    }

    static boolean isArmstrong(int n) {
        int original = n, sum = 0, digits = String.valueOf(n).length();
        while (n > 0) {
            sum += (int) Math.pow(n % 10, digits);
            n /= 10;
        }
        return sum == original;
    }

    static long factorial(int n) {
        return n <= 1 ? 1 : n * factorial(n - 1);
    }

    public static void main(String[] args) {
        ArrayList<Integer> primes = new ArrayList<>();
        for (int i = 1; i <= 50; i++) {
            if (isPrime(i)) primes.add(i);
        }
        System.out.println("primes up to 50: " + primes);

        System.out.print("Armstrong numbers up to 999: ");
        for (int i = 1; i < 1000; i++) {
            if (isArmstrong(i)) System.out.print(i + " ");
        }
        System.out.println();

        System.out.println("15! = " + factorial(15));

        for (int row = 1; row <= 4; row++) {
            for (int s = 0; s < 4 - row; s++) System.out.print(" ");
            for (int k = 0; k < row; k++) System.out.print("* ");
            System.out.println();
        }
    }
}
🖥️ Output:
primes up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Armstrong numbers up to 999: 1 2 3 4 5 6 7 8 9 153 370 371 407
15! = 1307674368000
*
* *
* * *
* * * *
  • An Armstrong number equals the sum of its digits, each raised to the number of digits: 153 = 1³ + 5³ + 3³.
  • Math.pow returns a double, so the result is cast to int (Lesson 9).
  • 15! needs long, because it is far larger than an int can hold (Lesson 26).
Mini-programTopics practised
Marks reportScanner, arrays, loops, methods, casting, if-else ladder
ATM menudo-while, switch, if, double arithmetic
Text toolsStrings, StringBuilder, methods, char tests
Number toolsmethods, loops, recursion, ArrayList, patterns

Figure 2: What each mini-program revises.

6️⃣ What to Do Next

  1. Type every program yourself. Do not copy and paste. Typing builds the habit.
  2. Change one thing and predict the result before you run it. Then read the error messages when you are wrong.
  3. Solve the practice questions at the end of each lesson.
  4. Build something small: a quiz, a library list, a student record system using classes and an ArrayList.
  5. Move on to the next topics: object-oriented programming in depth (inheritance, polymorphism, interfaces), the Collections Framework, file handling and lambdas.

✅ Final Takeaways

  • Every program is built from the same few pieces: variables, operators, decisions, loops, methods and objects.
  • Read error messages from the top. They tell you what and where.
  • Small programs that combine several ideas are the fastest way to revise.
  • Consistent practice beats long study sessions.
🎓 Final challenges: (1) Extend MarksReport so it asks for each subject’s name and prints a full report card. (2) Turn the ATM into a class Account with private balance and methods, and let the menu use an object. (3) Write a quiz program that stores questions in an ArrayList and counts correct answers. (4) Write a program that reads a sentence and prints the longest word. (5) Create a Student class with a constructor and an ArrayList<Student>, then print the topper.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision