Practice

Every practice problem from the thirteen topics in one place. Try each one before opening the answer.

1. Introducing OOP & Java Basics

1. Which primitive type would you use for a student ID like 2233051012? Why?
Show the answer
long — 2,233,051,012 is larger than the int maximum (2,147,483,647). (A String is also fine because we never do arithmetic on IDs.)
2. Evaluate (double) (5 / 2) and (double) 5 / 2.
Show the answer
2.0 and 2.5. In the first, integer division happens before the cast.
3. What is the value of (byte) 130?
Show the answer
−126. 130 − 256 = −126.
4. Write an if-else that prints “Leap” for leap years.
Show the answer
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
    System.out.println("Leap");
else
    System.out.println("Not leap");
5. A switch on month (1–12) must print the number of days. How can fall-through help?
Show the answer
Group cases with no break between them: case 4: case 6: case 9: case 11: days = 30; break; and case 2: days = 28; break;, default 31.
6. Give two differences between OOP and structured programming.
Show the answer
OOP bundles data with methods in objects (structured code keeps them separate); OOP hides data with access control (structured code often shares global data); OOP supports inheritance and polymorphism for reuse.
7. What does System.out.println(7 / 2 + 7 % 2 + 7 / 2.0); print?
Show the answer
  1. 7 / 2 = 3 (integer division).
  2. 7 % 2 = 1.
  3. 7 / 2.0 = 3.5 (a double operand).
  4. 3 + 1 + 3.5 = 7.5
8. Write one line that stores the larger of a and b in max.
Show the answer
int max = (a > b) ? a : b;
The ternary operator picks one of two values. Math.max(a, b) does the same.
9. What is printed? int x = 10; x += x++ + ++x; System.out.println(x);
Show the answer
  1. x += E means x = x + E; the left x is read first: 10.
  2. x++ gives 10, x becomes 11.
  3. ++x makes x 12 and gives 12.
  4. x = 10 + (10 + 12) = 32.

Open the topic 1 slides →

2. Iterative Statements

1. Write a loop that prints the sum of the even numbers from 1 to 100.
Show the answer
int s = 0;
for (int i = 2; i <= 100; i += 2) s += i;
System.out.println(s);   // 2550
2. Rewrite for (int i = 5; i > 0; i--) System.out.print(i); as a while loop.
Show the answer
int i = 5;
while (i > 0) {
    System.out.print(i);
    i--;
}
3. What is the output? int i = 10; do { i++; } while (i < 5); System.out.println(i);
Show the answer
11 — the body runs once before the condition is checked.
4. Print this pattern with nested loops:
1
1 2
1 2 3
Show the answer
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) System.out.print(j + " ");
    System.out.println();
}
5. Count the digits of a positive integer n using a while loop.
Show the answer
int count = 0;
while (n > 0) { n /= 10; count++; }
6. What is the difference between break and continue inside a nested loop?
Show the answer
break leaves the innermost loop entirely; continue skips to its next pass. Neither affects the outer loop unless you use a label.
7. How many times does Hi print? for (int i = 0; i < 10; i += 3) System.out.println("Hi");
Show the answer
i takes the values 0, 3, 6, 9 → 4 times. At i = 12 the condition is false.
8. Print all prime numbers from 2 to 30 using nested loops and continue with a label.
Show the answer
outer:
for (int n = 2; n <= 30; n++) {
    for (int d = 2; d * d <= n; d++)
        if (n % d == 0) continue outer;   // not prime
    System.out.print(n + " ");
}
Output
2 3 5 7 11 13 17 19 23 29
9. Keep asking for a PIN until the user types 1234, allowing at most 3 tries.
Show the answer
int tries = 0, pin;
do {
    System.out.print("PIN: ");
    pin = in.nextInt();
    tries++;
} while (pin != 1234 && tries < 3);
System.out.println(pin == 1234 ? "Welcome" : "Card blocked");

Open the topic 2 slides →

3. Arrays, Sorting & Searching

1. Write code to compute the average of a double[].
Show the answer
double s = 0;
for (double v : a) s += v;
double avg = s / a.length;
2. What is printed? int[] a = {1,2,3}; int[] b = a; b[1] = 9; System.out.println(a[1]);
Show the answer
9 — a and b refer to the same array.
3. Find the sum of each row of int[][] m.
Show the answer
for (int i = 0; i < m.length; i++) {
    int s = 0;
    for (int j = 0; j < m[i].length; j++) s += m[i][j];
    System.out.println("Row " + i + ": " + s);
}
4. Show selection sort on {29, 10, 14, 37, 13} pass by pass.
Show the answer
{10, 29, 14, 37, 13} → {10, 13, 14, 37, 29} → {10, 13, 14, 37, 29} → {10, 13, 14, 29, 37}.
5. What is the maximum number of comparisons binary search needs for 1,000 sorted elements?
Show the answer
10, because 210 = 1024 ≥ 1000.
6. Why does int[] a = new int[3]; System.out.println(a); print something like [I@1b6d3586?
Show the answer
Printing an array prints its type and hash code, not its elements. Use Arrays.toString(a).
7. Reverse an array in place.
Show the answer
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
    int t = a[i]; a[i] = a[j]; a[j] = t;
}
Swap the two ends and move inwards; stop when the indexes meet. Only n/2 swaps.
8. Show the array after each pass of bubble sort on {5, 1, 4, 2}.
Show the answer
  1. Pass 1: {1, 4, 2, 5}
  2. Pass 2: {1, 2, 4, 5}
  3. Pass 3: {1, 2, 4, 5} (no swaps — already sorted)
9. Binary search for 23 in {2, 5, 8, 12, 16, 23, 38, 56}. List lo, hi, mid for each step.
Show the answer
  1. lo=0, hi=7, mid=3 → 12 < 23 → lo = 4
  2. lo=4, hi=7, mid=5 → 23 found at index 5
Only 2 comparisons, against up to 6 for a linear search.

Open the topic 3 slides →

4. Classes, Objects & Encapsulation

1. What is the difference between a class and an object?
Show the answer
A class is the definition (blueprint, written once in code); an object is an instance of it created at run time with its own field values. One class → many objects.
2. Write a BankAccount class whose withdraw refuses to go below 0.
Show the answer
public boolean withdraw(double amt) {
    if (amt <= 0 || amt > balance) return false;
    balance -= amt;
    return true;
}
3. What are the default values of the fields int n; boolean b; String s; double d; in a new object?
Show the answer
0, false, null, 0.0. (Local variables have no defaults and must be assigned before use.)
4. Fix the constructor: Point(int x, int y) { x = x; y = y; }
Show the answer
this.x = x; this.y = y;
5. After Student a = new Student("A"); a = new Student("B");, what happens to the object "A"?
Show the answer
It has no reference left, so it becomes eligible for garbage collection.
6. Why should fields be private?
Show the answer
So other classes cannot put the object into an invalid state; all changes go through methods that can validate. It also lets you change the internal representation without breaking other code.
7. Design a Rectangle class with private width and height, a constructor, area() and perimeter().
Show the answer
public class Rectangle {
    private double width, height;
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    public double area()      { return width * height; }
    public double perimeter() { return 2 * (width + height); }
}
8. How many objects are created, and how many are eligible for GC at the end?
A a = new A(); A b = new A(); A c = a; a = b; b = null;
Show the answer
  1. Two objects: #1 (first new) and #2.
  2. c → #1, a → #2, b → null.
  3. Both are still referenced → 0 eligible.
9. Why does this fail to compile? class P { P(int x) {} } … P p = new P();
Show the answer
Writing P(int x) removes the automatic default constructor, so there is no P(). Add P() {} or call new P(5).

Open the topic 4 slides →

5. Overloading, Objects as Parameters & Recursion

1. Are void f(int a, double b) and void f(double a, int b) valid overloads? Is f(1, 2) OK?
Show the answer
Yes, they are valid overloads (different order). But f(1, 2) is ambiguous — each needs one widening — so it does not compile.
2. Write constructors for Time: Time() = 00:00, Time(h), Time(h, m), using this(...).
Show the answer
Time() { this(0, 0); }
Time(int h) { this(h, 0); }
Time(int h, int m) { this.h = h; this.m = m; }
3. A method does arr[0] = 99; on an array parameter. Does the caller see it?
Show the answer
Yes. The parameter refers to the same array object.
4. Write a recursive gcd(a, b).
Show the answer
static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
5. How many calls does naive fib(5) make in total?
Show the answer
15 calls (fib(5) → fib(4), fib(3) … count every node of the call tree).
6. Write a method Point midpoint(Point p) that returns a new Point halfway between this and p.
Show the answer
Point midpoint(Point p) {
    return new Point((x + p.x) / 2, (y + p.y) / 2);
}
7. Which method is called by print(5) if the class has only print(long x) and print(Integer x)?
Show the answer
print(long). Widening (int → long) is preferred over boxing (int → Integer).
8. What does this print?
static void swap(int a, int b) { int t = a; a = b; b = t; }
int x = 1, y = 2; swap(x, y); System.out.println(x + " " + y);
Show the answer
1 2. swap received copies of the values; the caller’s variables never change. (Java cannot write a swap for two int variables.)
9. Write a recursive method that counts how many times a character occurs in a String.
Show the answer
static int count(String s, char c) {
    if (s.isEmpty()) return 0;
    return (s.charAt(0) == c ? 1 : 0) + count(s.substring(1), c);
}
// count("banana", 'a') → 3

Open the topic 5 slides →

6. Access Control, static, final & Nested Classes

1. What is the difference between default (package-private) and protected access?
Show the answer
Both allow access within the same package; protected additionally allows subclasses in other packages.
2. Can a static method call an instance method directly? Explain.
Show the answer
No — an instance method needs an object (this), and a static method has none. It must create or receive an object first: obj.method().
3. Is this legal? final StringBuilder sb = new StringBuilder(); sb.append("x");
Show the answer
Yes. final fixes the reference, not the object. sb = new StringBuilder(); would be illegal.
4. Write a class Circle that counts how many circles exist and exposes the count with a static getter.
Show the answer
class Circle {
    private static int count;
    private double r;
    Circle(double r) { this.r = r; count++; }
    static int getCount() { return count; }
}
5. How do you create an object of an inner class Inner defined in Outer?
Show the answer
Outer o = new Outer(); Outer.Inner in = o.new Inner(); — an inner object always needs an outer object.
6. Why is Math’s constructor private?
Show the answer
All its members are static, so objects are pointless; a private constructor prevents new Math().
7. Why does this not compile?
class A { int x; static void show() { System.out.println(x); } }
Show the answer
show() is static, so it runs without any object — there is no this.x to print. Make show() an instance method, or make x static, or pass an A object as a parameter.
8. Class Pay in package hr declares protected double rate;. Which classes can use rate?
Show the answer
  • Pay itself.
  • Every class in package hr.
  • Subclasses of Pay in other packages — through inheritance (their own objects).
  • No other classes.
9. Give each Order a unique, unchangeable number 1001, 1002, …
Show the answer
class Order {
    private static int next = 1001;
    private final int no;
    Order() { no = next++; }
    int getNo() { return no; }
}
A static counter shared by all orders, and a final instance field set once in the constructor.

Open the topic 6 slides →

7. Inheritance

1. Why does Java not allow class C extends A, B?
Show the answer
To avoid the diamond problem: if A and B both define the same method, C would inherit two conflicting versions. Interfaces are used for multiple inheritance of type.
2. Can a subclass access a private field of its superclass directly?
Show the answer
No. The field is inherited (it is inside the object) but not accessible; use a protected or public getter/setter.
3. Write Manager extends Employee with an extra bonus, overriding salary() using super.salary().
Show the answer
class Manager extends Employee {
    private double bonus;
    Manager(String n, double base, double bonus) { super(n, base); this.bonus = bonus; }
    @Override double salary() { return super.salary() + bonus; }
}
4. What does System.out.println(obj) print if the class does not override toString()?
Show the answer
ClassName@hexHashCode, e.g. Student@7a81197d.
5. Name the relationship: Library – Book, Dog – Animal, Car – Wheel, Square – Rectangle.
Show the answer
has-a, is-a, has-a, is-a (with care: a Square “is a” Rectangle mathematically, but changing width alone breaks it — a classic design trap).
6. In which order do constructors and field initialisers run for new C() in A → B → C?
Show the answer
A’s fields and constructor, then B’s, then C’s — from the top of the hierarchy down.
7. What is printed?
class A { A() { System.out.print("A"); } }
class B extends A { B() { System.out.print("B"); } }
class C extends B { C() { super(); System.out.print("C"); } }
new C();
Show the answer
ABC. Every constructor calls its superclass constructor first.
8. Why does this fail? class P { P(int x) {} } class Q extends P { Q() {} }
Show the answer
Q() implicitly calls super(), but P has no no-arg constructor. Fix: Q() { super(0); }.
9. Draw the UML and write the classes: Shape has color; Circle is a Shape with radius; both have constructors.
Show the answer
class Shape {
    protected String color;
    Shape(String color) { this.color = color; }
}
class Circle extends Shape {
    private double radius;
    Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }
}
UML: Circle → (hollow triangle) → Shape.

Open the topic 7 slides →

8. Overriding, Polymorphism & Abstract Classes

1. State three rules a method must follow to override another.
Show the answer
Same name and parameter list; return type the same or a subtype; access not more restrictive; cannot throw broader checked exceptions; the original must not be final, static or private.
2. Can an abstract class have a constructor? Why?
Show the answer
Yes. It runs when a subclass object is created (via super(...)) to initialise the abstract class’s fields.
3. What is printed? Shape s = new Circle(1); System.out.println(s instanceof Shape);
Show the answer
true — a Circle is a Shape.
4. Why is String declared final?
Show the answer
So no subclass can change its behaviour (for example make it mutable), which keeps strings safe to share, cache and use as keys.
5. Write a loop that calls speak() only on the Dogs in an Animal[].
Show the answer
for (Animal a : zoo)
    if (a instanceof Dog d)   // Java 16 pattern
        d.speak();
6. Is overloading resolved at compile time or run time? Overriding?
Show the answer
Overloading at compile time (static binding); overriding at run time (dynamic binding).
7. What is printed?
class A { void f() { System.out.print("A"); } }
class B extends A { void f() { System.out.print("B"); } }
A x = new B(); x.f(); ((A) x).f();
Show the answer
BB. Casting the reference does not change the object; dispatch still picks B.f().
8. Given Animal a = new Dog();, what happens with (1) Dog d = a; (2) Dog d = (Dog) a; (3) Cat c = (Cat) a;?
Show the answer
  1. Does not compile: an Animal is not necessarily a Dog.
  2. Compiles and works.
  3. Compiles, but throws ClassCastException at run time because the object is a Dog.
9. Design an abstract Employee with abstract earnings() and two concrete subclasses.
Show the answer
abstract class Employee {
    protected String name;
    Employee(String name) { this.name = name; }
    abstract double earnings();
}
class Salaried extends Employee {
    private double monthly;
    Salaried(String n, double m) { super(n); monthly = m; }
    double earnings() { return monthly; }
}
class Hourly extends Employee {
    private double rate; private int hours;
    Hourly(String n, double r, int h) { super(n); rate = r; hours = h; }
    double earnings() { return rate * hours; }
}

Open the topic 8 slides →

9. Packages & Interfaces

1. What is the purpose of the package statement and where must it appear?
Show the answer
It puts the class in a named package (a namespace and folder); it must be the first statement in the file (only comments may come before it).
2. A field is declared with no modifier in package a. Can a subclass in package b use it?
Show the answer
No — default access is package-only. It would need to be protected or public.
3. Write an interface Resizable with void resize(double factor) and implement it in Circle.
Show the answer
interface Resizable { void resize(double factor); }
class Circle implements Resizable {
    private double r;
    public void resize(double f) { r *= f; }
}
4. Can an interface have a constructor? A field that changes?
Show the answer
No constructor. Fields are implicitly public static final constants, so they cannot change.
5. Give one reason to prefer an interface over an abstract class.
Show the answer
A class can implement many interfaces but extend only one class; interfaces let unrelated classes share a role.
6. What happens if a class implements two interfaces that both have default void hello()?
Show the answer
Compile error unless the class overrides hello(); inside it can pick one with A.super.hello().
7. Why does this not compile? interface Shape { double area(); } class Sq implements Shape { double area() { return 4; } }
Show the answer
Interface methods are public; area() in Sq has default (package) access, which is weaker. Write public double area().
8. A class Robot must be both Movable and Chargeable, and it already extends Machine. Write the header.
Show the answer
class Robot extends Machine implements Movable, Chargeable { ... }
extends comes first; any number of interfaces follow implements.
9. What does this print? interface I { int X = 10; } class A implements I { } System.out.println(A.X + I.X);
Show the answer
20. X is a public static final constant inherited by A.

Open the topic 9 slides →

10. Exception Handling

1. Classify as checked or unchecked: FileNotFoundException, NullPointerException, SQLException, NumberFormatException.
Show the answer
Checked, unchecked, checked, unchecked.
2. Why is catch (Exception e) followed by catch (IOException e) a compile error?
Show the answer
IOException is a subclass of Exception, so the second catch can never be reached.
3. Write a method sqrt(double x) that throws IllegalArgumentException for negative x.
Show the answer
static double sqrt(double x) {
    if (x < 0) throw new IllegalArgumentException("negative: " + x);
    return Math.sqrt(x);
}
4. When does a finally block NOT run?
Show the answer
Practically only if the JVM stops (System.exit, crash, power loss) or the thread is killed while inside try/catch.
5. Create an unchecked exception InvalidMarksException.
Show the answer
class InvalidMarksException extends RuntimeException {
    InvalidMarksException(String msg) { super(msg); }
}
6. What does the stack trace line at Main.main(Main.java:14) tell you?
Show the answer
The exception passed through method main of class Main, at line 14 of Main.java.
7. What is printed?
try { System.out.print("A"); int x = 5 / 0; System.out.print("B"); }
catch (ArithmeticException e) { System.out.print("C"); }
finally { System.out.print("D"); } System.out.print("E");
Show the answer
ACDE. B is skipped; the catch handles the exception; finally always runs; the program continues.
8. What does f() return? static int f() { try { return 1; } finally { System.out.print("F"); } }
Show the answer
It prints F and returns 1. finally runs just before the method actually returns.
9. Make readScore keep asking until the user types a valid integer.
Show the answer
static int readScore(Scanner in) {
    while (true) {
        try {
            return Integer.parseInt(in.nextLine().trim());
        } catch (NumberFormatException e) {
            System.out.println("Please type a whole number.");
        }
    }
}

Open the topic 10 slides →

11. Multithreaded Programming

1. Give two ways to create a thread and one reason to prefer Runnable.
Show the answer
Extend Thread or implement Runnable (or use a lambda). Runnable lets the class extend another class and separates the task from the thread.
2. Which state is a thread in while inside Thread.sleep(500)?
Show the answer
TIMED_WAITING.
3. Write code that starts 3 threads printing their names and waits for all before printing “done”.
Show the answer
Thread[] ts = new Thread[3];
for (int i = 0; i < 3; i++) {
    ts[i] = new Thread(() -> System.out.println(Thread.currentThread().getName()), "T" + i);
    ts[i].start();
}
for (Thread t : ts) t.join();
System.out.println("done");
4. Why is count++ not thread-safe?
Show the answer
It is a read, an add and a write; another thread can run between them and one update is lost.
5. What is the difference between sleep() and wait()?
Show the answer
sleep pauses without releasing any lock and is called on Thread; wait must hold the object’s lock, releases it, and waits for notify.
6. State one rule that prevents deadlock.
Show the answer
Acquire locks in a fixed global order in every thread.
7. What is wrong? Thread t = new Thread(task); t.run();
Show the answer
run() executes the task in the current thread like a normal method call. Use t.start() to create a new thread.
8. Two threads each call synchronized void inc() 1000 times on the same object. What is the final count? What if each thread uses its own object?
Show the answer
Same object: always 2000. Different objects: each counter reaches 1000; the locks are different but so is the data, so there is no race.
9. Why should wait() be called in a while loop rather than an if?
Show the answer
A thread can wake up when the condition is still false (another thread got there first, or a spurious wake-up). The while loop re-checks before continuing.

Open the topic 11 slides →

12. Strings & Big Numbers

1. Why does new String("a") == "a" give false?
Show the answer
new String creates a separate object on the heap; == compares references, and the literal is the pooled object.
2. Write a method that checks whether a String is a palindrome, ignoring case.
Show the answer
static boolean isPal(String s) {
    s = s.toLowerCase();
    for (int i = 0, j = s.length() - 1; i < j; i++, j--)
        if (s.charAt(i) != s.charAt(j)) return false;
    return true;
}
3. What does "Programming".substring(3, 7) return?
Show the answer
"gram" (indexes 3, 4, 5, 6).
4. Give the result of "cat".compareTo("car").
Show the answer
2 ('t' 116 − 'r' 114).
5. Write subtract(String a, String b) for a ≥ b ≥ 0.
Show the answer
static String subtract(String a, String b) {
    StringBuilder sb = new StringBuilder();
    int borrow = 0;
    for (int i = a.length() - 1, j = b.length() - 1; i >= 0; i--, j--) {
        int d = a.charAt(i) - '0' - borrow - (j >= 0 ? b.charAt(j) - '0' : 0);
        borrow = d < 0 ? 1 : 0;
        sb.append(d < 0 ? d + 10 : d);
    }
    String r = sb.reverse().toString().replaceFirst("^0+(?!$)", "");
    return r;
}
6. When should you use StringBuilder instead of String?
Show the answer
When you build a string step by step, especially inside loops, to avoid creating many temporary String objects.
7. What is printed? String s = "java"; s.toUpperCase(); System.out.println(s);
Show the answer
java. toUpperCase returns a new String that is thrown away. Write s = s.toUpperCase();.
8. Count the words in a sentence that may contain several spaces between words.
Show the answer
String t = "  OOP   is   fun ";
String[] w = t.trim().split("\\s+");     // one or more spaces
System.out.println(w.length);            // 3
9. Add "999" and "1" with the string algorithm. Show each column.
Show the answer
  1. 9 + 1 + 0 = 10 → write 0, carry 1
  2. 9 + 0 + 1 = 10 → write 0, carry 1
  3. 9 + 0 + 1 = 10 → write 0, carry 1
  4. carry 1 left → write 1
Reverse "0001" → "1000".

Open the topic 12 slides →

13. GUI, Graphics, Databases & Spring

1. What are Stage, Scene and Node in JavaFX?
Show the answer
Stage is the window; Scene is the content shown in it; Nodes are the objects (panes, controls, shapes) in the scene graph tree.
2. Write code that draws a red circle of radius 40 centred at (100, 100) on a GraphicsContext gc.
Show the answer
gc.setFill(Color.RED);
gc.fillOval(60, 60, 80, 80);   // top-left corner, width, height
3. Why must slow work (like a database query) not run inside an event handler on the JavaFX Application Thread?
Show the answer
The UI thread would be blocked, so the window freezes. Run the work in a background thread (e.g. a Task) and update the UI with Platform.runLater.
4. What is the difference between executeQuery and executeUpdate?
Show the answer
executeQuery runs a SELECT and returns a ResultSet; executeUpdate runs INSERT/UPDATE/DELETE and returns the number of affected rows.
5. Explain dependency injection in one sentence.
Show the answer
Instead of an object creating the objects it needs, they are passed to it (usually through the constructor) by a container such as Spring.
6. How does an AnimationTimer create smooth motion?
Show the answer
Its handle(now) method is called about 60 times per second; each call updates positions slightly and redraws the frame.
7. Which layout pane would you use for a login form with labels in one column and fields in the next?
Show the answer
GridPane — it places nodes in rows and columns: g.add(new Label("User"), 0, 0); g.add(userField, 1, 0);.
8. Write a handler that shows the length of the text typed in TextField tf in Label lb whenever the user presses Enter.
Show the answer
tf.setOnAction(e -> lb.setText("Length: " + tf.getText().length()));
For a TextField, setOnAction fires when Enter is pressed.
9. Loop through a ResultSet and build a list of Student objects.
Show the answer
List<Student> list = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
    while (rs.next())
        list.add(new Student(rs.getString("name"), rs.getDouble("cgpa")));
}
Each row becomes one object — the bridge between tables and OOP.

Open the topic 13 slides →