🎓 A1Learner
🔍

Home / Blog / Programming / Java

Top 50 Java Interview Questions with Answers

Programming · Java · 32 min read

Fifty Java interview questions with answers. Every program was compiled and run on OpenJDK 21: basics, OOP, collections, exceptions, and threads.

How this sheet works

This page holds fifty Java interview questions, sorted into groups by topic. Basics come first, then strings, loops, and arrays. Methods and objects follow, then collections, exceptions, and threads. The last six questions are small coding tasks to write out by hand.

Every program below was compiled and run on Temurin OpenJDK 21.0.13, and the page shows the exact lines each run printed. No output here is invented. One program writes its own file and reads it back, so it runs in an empty folder. The thread program waits for its worker to finish, so the printed order never changes. One more program fails to compile on purpose: it reaches for a private field, and the page shows the compiler's own error instead of output.

Take one question at a time. Hide the answer, say yours aloud, then read the page version and compare the two. Then type the program out yourself and run it. An answer you can say and a program you can run will both stay with you longer than an answer you only read.

The Java track here holds 118 lessons: 48 in Beginner, 40 in Intermediate, and 30 in Advanced. Every answer below names the lesson behind the idea, so a miss shows you exactly what to read next. When an answer draws on two lessons, both are named.

Two honest limits. Spring Boot, Android apps, and database access appear in neither the Java track nor this sheet, so this sheet has nothing to say about them. The threads answer starts one worker thread; the Advanced lessons named there cover executors, locks, and the rest of the thread toolkit.

1. What is Java, and what is it used for?

Java is a language for building programs that run in many places. Banks, shops, and phone makers all use it, and the same code can run on a laptop and on a server. The trick is a middle layer: Java code runs on the Java Virtual Machine, and the machine runs on the computer.

People choose Java when a program must keep running for years and many hands will touch it. The language is strict about types, so a whole class of mistakes is caught before the program runs. Its standard library is large, so everyday jobs like reading files and talking over a network need no extra downloads.

The Java Introduction lesson opens the course with a first program and a first message on the screen.

2. What are the JDK, the JRE, and the JVM?

The three letters name three layers. The JDK is the kit for writing Java: it holds the compiler, which turns source files into bytecode. The JRE is the kit for running Java: it holds the JVM and the standard library. The JVM is the machine that runs the bytecode.

A programmer installs the JDK. It includes everything the JRE holds, plus the compiler and the other tools for writing code, so one install covers both writing and running. A person who only runs Java programs needs the JRE alone, though in practice the JDK is the usual install.

The Java Get Started lesson shows how a file becomes a running program. The Java Inside the JVM lesson opens up the JVM itself and shows what happens to bytecode after it loads.

3. What does a first Java program look like?

Every Java program lives inside a class. The smallest program has one class, called Main, and one method inside it, called main. The program starts at main and runs its lines from top to bottom.

The program below prints one greeting. The first line is a comment: it starts with two slashes, and the compiler skips it. The println line does the work. The file must be saved as Main.java, because the file name matches the class name.

The Java Introduction lesson builds this same first program step by step. The Java Comments lesson covers the comment line on its own.

// This line is a comment. The compiler ignores it.
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

Output:
Hello, World!

4. What is the main method, and what does String[] args do?

The main method is the front door of a Java program. When you run a class, the JVM looks for main and starts there. A program without a main method has nowhere to begin, and the JVM refuses to run it.

The words around main each do a job. public means the JVM can reach it. static means it runs without an object. void means it returns nothing. String[] args holds the words typed after the class name on the command line, and the program below prints how many arrived. Running it with no words gives zero.

The Java Introduction lesson opens with main and its first message. The Java Get Started lesson shows the compile-and-run steps that call it.

public class Main {
  public static void main(String[] args) {
    System.out.println("Arguments: " + args.length);
    System.out.println("Hello, World!");
  }
}

Output:
Arguments: 0
Hello, World!

5. How do you print a value in Java?

With System.out.println. The call prints a value and then moves to a new line. System.out.print prints without the new line, so the next print continues on the same line. System.out.printf prints a template with values slotted into it.

The program below prints with all three. print puts two words on one line. println starts a fresh line. printf fills in two numbers from a template, and %d marks a whole-number slot.

The Java Output lesson works through all three calls with more cases.

public class Main {
  public static void main(String[] args) {
    System.out.print("One ");
    System.out.print("Two");
    System.out.println();
    System.out.println("Three");
    System.out.printf("Score: %d out of %d%n", 8, 10);
  }
}

Output:
One Two
Three
Score: 8 out of 10

6. What is a variable, and how do you declare one?

A variable is a named box that holds one value. The declaration names the kind of value first, then the name. int age = 9 makes a box called age that holds whole numbers, and starts it at 9. The program can read the box and write a new value into it later.

The name is the programmer's choice, but the kind is a promise. An int box holds whole numbers only. A double box holds numbers with a fraction. A boolean box holds true or false. A String box holds text. Putting the wrong kind of value into a box is a compile error, not a surprise at run time.

The Java Variables lesson declares each kind with its own example.

public class Main {
  public static void main(String[] args) {
    int age = 9;
    double price = 4.99;
    boolean ready = true;
    String name = "Ana";
    System.out.println(name);
    System.out.println(age);
    System.out.println(price);
    System.out.println(ready);
  }
}

Output:
Ana
9
4.99
true

7. What are the primitive data types?

Java has eight primitive types: four for whole numbers, two for fractions, one for single characters, and one for true-or-false. byte, short, int, and long cover whole numbers of different sizes. float and double cover fractions. char holds one character. boolean holds true or false.

The sizes matter. An int holds whole numbers up to about two billion, and the program below prints its exact top and bottom. A long holds far larger numbers, and a long value ends with the letter L. A float ends with F. Anything else is not a primitive: String is a class, not one of the eight.

The Java Data Types lesson names all eight types with a short example each. The Java Numbers lesson shows the ranges each whole-number type covers.

public class Main {
  public static void main(String[] args) {
    byte small = 100;
    short medium = 30000;
    int count = 2000000000;
    long big = 9000000000L;
    float ratio = 1.5f;
    double precise = 1.5;
    char letter = 'A';
    boolean yes = true;
    System.out.println(small);
    System.out.println(medium);
    System.out.println(count);
    System.out.println(big);
    System.out.println(ratio);
    System.out.println(precise);
    System.out.println(letter);
    System.out.println(yes);
    System.out.println(Integer.MAX_VALUE);
    System.out.println(Integer.MIN_VALUE);
  }
}

Output:
100
30000
2000000000
9000000000
1.5
1.5
A
true
2147483647
-2147483648

8. What is type casting, and when does it lose data?

Type casting changes a value from one type to another. Widening moves to a bigger type, and it never loses anything: an int fits inside a double with room to spare. Narrowing moves to a smaller type, and it can lose data: turning 9.99 into an int drops the fraction and leaves 9.

The same trap hides in plain division. 5 / 2 gives 2, because both numbers are ints and int division drops the remainder. Writing one number with a decimal point, 5.0 / 2, gives 2.5. The program below shows both, so the difference is visible.

The Java Type Casting lesson works through widening and narrowing with more cases.

public class Main {
  public static void main(String[] args) {
    int whole = 7;
    double wide = whole;
    System.out.println(wide);
    double price = 9.99;
    int rounded = (int) price;
    System.out.println(rounded);
    System.out.println(5 / 2);
    System.out.println(5.0 / 2);
    System.out.println(5 / 2.0);
  }
}

Output:
7.0
9
2
2.5
2.5

9. What are the Java operators, and what does each group do?

Operators are the verbs of Java. The arithmetic group does sums: + adds, - subtracts, * multiplies, / divides, and % gives the remainder. The comparison group asks questions: > asks if one value is bigger, and == asks if two values are equal. The logic group joins true-or-false values: && needs both sides true, || needs one side true, and ! flips a value.

Two small operators deserve care. ++ adds one to a variable, and it is the usual way to step a loop. = puts a value into a variable, while == compares two values, and mixing the two up is a classic first mistake. The program below prints the result of each group, so the answers are visible rather than guessed.

The full set lives in the Java Operators lesson.

public class Main {
  public static void main(String[] args) {
    System.out.println(10 + 3);
    System.out.println(10 - 3);
    System.out.println(10 * 3);
    System.out.println(10 / 3);
    System.out.println(10 % 3);
    System.out.println(10 > 3);
    System.out.println(10 == 3);
    System.out.println(true && false);
    System.out.println(true || false);
    System.out.println(!true);
    int n = 5;
    n++;
    System.out.println(n);
  }
}

Output:
13
7
30
3
1
true
false
false
true
false
6

10. What is a String, and how is it different from a char?

A String holds text of any length. A char holds exactly one character, written between single quotes. 'J' is a char. "Java" is a String. The two kinds are not interchangeable: a method that wants a String will not accept a char, and the reverse is also true.

Strings carry useful methods. length counts the characters. charAt picks one out by position, counting from zero. + joins two strings into one. The program below prints the length of "Java", its first character, and the joined result.

The Java Strings lesson covers the common methods. The Java Characters lesson covers the single-character kind.

public class Main {
  public static void main(String[] args) {
    String word = "Java";
    char first = 'J';
    System.out.println(word);
    System.out.println(word.length());
    System.out.println(word.charAt(0));
    System.out.println(first);
    System.out.println(word + "!");
  }
}

Output:
Java
4
J
J
Java!

11. What is the difference between == and equals()?

For numbers, == compares values, and 5 == 5 is true. For objects, == checks identity, not content: it is true only when both names point at the very same object. Two strings can hold the same letters and still be different objects.

equals compares content. The program below makes two strings with the same letters in two ways. The two written as literals share one pooled object, so == says true. The one built with new is a separate object, so == says false, while equals says true. That split is the whole lesson: == asks same object, equals asks same content.

The Java Strings lesson shows both tests side by side. The Java equals and hashCode lesson explains why equal objects must also share a hash code.

public class Main {
  public static void main(String[] args) {
    String a = "Ana";
    String b = "Ana";
    String c = new String("Ana");
    System.out.println(a == b);
    System.out.println(a == c);
    System.out.println(a.equals(c));
    int x = 5;
    int y = 5;
    System.out.println(x == y);
  }
}

Output:
true
false
true
true

12. Why use a StringBuilder instead of + in a loop?

Strings never change. Joining two strings builds a third string and leaves the first two untouched. In a loop that joins a thousand times, a thousand throwaway strings are built and dropped, and the work adds up.

A StringBuilder is a box that changes. append adds text to the same box, and toString reads the finished result out of it at the end. The program below builds "red fish" that way, then reverses the same box in place. When the text is built once, + is fine. When it grows in a loop, reach for the builder.

The Java StringBuilder lesson builds longer strings the same way.

public class Main {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append("red");
    sb.append(" ");
    sb.append("fish");
    System.out.println(sb.toString());
    System.out.println(sb.length());
    sb.reverse();
    System.out.println(sb.toString());
  }
}

Output:
red fish
8
hsif der

13. How does if...else choose between paths?

if...else picks one path by testing a condition. The first branch whose condition is true runs, and the rest are skipped. else if adds more branches. A final else catches everything the earlier branches missed.

The program below grades a score of 85. The first test fails, the second passes, and B is printed. The last line uses the short form: score >= 50 ? "Pass" : "Fail" picks one of two values in a single expression.

The Java If...Else lesson grades more scores the same way.

public class Main {
  public static void main(String[] args) {
    int score = 85;
    if (score >= 90) {
      System.out.println("A");
    } else if (score >= 80) {
      System.out.println("B");
    } else if (score >= 70) {
      System.out.println("C");
    } else {
      System.out.println("Try again");
    }
    System.out.println(score >= 50 ? "Pass" : "Fail");
  }
}

Output:
B
Pass

14. How does a switch statement work?

A switch statement picks one branch by matching a value. The value is tested against each case label in turn. The first matching label runs, and break stops the run there. Without break, the run falls through into the next label, which is rarely what anyone wants.

The program below switches on the number 3 and prints Wednesday. A default label catches every value no case names. Switch works with whole numbers, characters, strings, and enums.

The Java Switch lesson works through more values.

public class Main {
  public static void main(String[] args) {
    int day = 3;
    switch (day) {
      case 1:
        System.out.println("Monday");
        break;
      case 2:
        System.out.println("Tuesday");
        break;
      case 3:
        System.out.println("Wednesday");
        break;
      default:
        System.out.println("Another day");
    }
  }
}

Output:
Wednesday

15. What is the difference between a while loop and a for loop?

Both loops repeat a block. A while loop tests its condition first and repeats until the test fails, which suits a job with no known count. A for loop packs the start, the test, and the step into one header, which suits counting through a known range.

Two words steer a loop from inside. break stops the loop at once, and the program below stops counting at 4. continue jumps to the next pass early, skipping the lines left in this one, and the program skips 2. The program shows all three: a while loop, a for loop, and both steering words.

The Java While Loop lesson and the Java For Loop lesson each build their own loops. The Java Break and Continue lesson steers them.

public class Main {
  public static void main(String[] args) {
    int n = 1;
    while (n <= 3) {
      System.out.println("while: " + n);
      n++;
    }
    for (int i = 1; i <= 3; i++) {
      if (i == 2) {
        continue;
      }
      System.out.println("for: " + i);
    }
    for (int i = 1; i <= 5; i++) {
      if (i == 4) {
        break;
      }
      System.out.println("count: " + i);
    }
  }
}

Output:
while: 1
while: 2
while: 3
for: 1
for: 3
count: 1
count: 2
count: 3

16. How do arrays work?

An array holds a fixed number of values of one kind, in numbered slots starting at zero. int[] scores = {82, 95, 71} makes three slots. scores[0] reads the first. scores[1] = 90 writes a new value into the second. scores.length says how many slots there are.

The size is fixed at creation. An array cannot grow, and reading past the end throws an error. The program below reads two slots, changes one, prints the whole array, and adds all three values with a for-each loop, which visits each slot in turn without an index.

The Java Arrays lesson builds more arrays. The Java Multidimensional Arrays lesson adds a second dimension.

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] scores = {82, 95, 71};
    System.out.println(scores.length);
    System.out.println(scores[0]);
    System.out.println(scores[2]);
    scores[1] = 90;
    System.out.println(Arrays.toString(scores));
    int total = 0;
    for (int s : scores) {
      total += s;
    }
    System.out.println(total);
  }
}

Output:
3
82
71
[82, 90, 71]
243

17. What is a method, and why write one?

A method is a named piece of code that carries out one task. The program calls it by name whenever that task is needed, instead of repeating the same lines. A method can take values in and hand a value back, or it can simply do something, like print a greeting.

The program below has two methods. add takes two numbers and returns their sum. greet takes a name and prints a greeting, returning nothing. main calls both, and the same add method serves two different pairs of numbers.

The Java Methods lesson writes more methods the same way.

public class Main {
  static int add(int a, int b) {
    return a + b;
  }

  static void greet(String name) {
    System.out.println("Hello, " + name);
  }

  public static void main(String[] args) {
    System.out.println(add(2, 3));
    System.out.println(add(10, 20));
    greet("Ana");
  }
}

Output:
5
30
Hello, Ana

18. What are method parameters and return values?

Parameters are the values a method takes in. They are declared in the method header, with a kind and a name each. area takes a width and a height, both doubles, and returns their product. The caller passes real values, and the method works with copies of them.

return hands a value back and ends the method at once. A method that returns nothing is marked void, and it ends when its lines run out. The program below prints an area twice: once from the returned value, once through a void method that prints it itself.

The Java Method Parameters lesson passes more values in more ways.

public class Main {
  static double area(double width, double height) {
    return width * height;
  }

  static void printArea(double width, double height) {
    System.out.println(area(width, height));
  }

  public static void main(String[] args) {
    System.out.println(area(3, 4));
    printArea(2.5, 4);
  }
}

Output:
12.0
10.0

19. What is method overloading?

Overloading means writing several methods with one name and different parameter lists. The compiler picks the version whose parameters match the call. add with two ints adds whole numbers. add with two doubles adds fractions. add with two strings joins them.

The return type alone cannot tell two versions apart. Two methods with the same name and the same parameters but different return types are a compile error. Only the parameter list counts: how many parameters, and of which kinds.

The Java Method Overloading lesson shows more overloaded names.

public class Main {
  static int add(int a, int b) {
    return a + b;
  }

  static double add(double a, double b) {
    return a + b;
  }

  static String add(String a, String b) {
    return a + b;
  }

  public static void main(String[] args) {
    System.out.println(add(2, 3));
    System.out.println(add(2.5, 3.5));
    System.out.println(add("red ", "fish"));
  }
}

Output:
5
6.0
red fish

20. What is scope in Java?

Scope is the reach of a name. A variable declared inside a method lives in that method. A variable declared inside a loop lives in that loop. Code outside cannot see it, and using it there is a compile error.

A class-level field lives wider. The program below declares shared at class level, and both main and show can read it. The variable local lives inside show, and only show can read it. The loop counter i lives inside its for header, and dies when the loop ends.

The Java Scope lesson maps every kind of scope side by side.

public class Main {
  static int shared = 10;

  static void show() {
    int local = 5;
    System.out.println(local);
    System.out.println(shared);
  }

  public static void main(String[] args) {
    show();
    System.out.println(shared);
    for (int i = 0; i < 2; i++) {
      System.out.println(i);
    }
  }
}

Output:
5
10
10
0
1

21. What is recursion?

Recursion is a method that calls itself to finish its own job. Each call takes a smaller slice of the work, until a slice is small enough to answer at once. factorial(5) is 5 times factorial(4), which is 4 times factorial(3), and so on down to factorial(1), which is 1.

Every recursive method needs a stopping case. Here it is n <= 1, which returns 1. Without it, the calls never stop, and the program exhausts the stack and crashes. The program below prints factorial(5) and factorial(0), both through the same two-line method.

The Java Recursion lesson counts down the same way.

public class Main {
  static int factorial(int n) {
    if (n <= 1) {
      return 1;
    }
    return n * factorial(n - 1);
  }

  public static void main(String[] args) {
    System.out.println(factorial(5));
    System.out.println(factorial(0));
  }
}

Output:
120
1

22. What is a class, and how is an object different?

A class is a blueprint. It lists the fields each object carries and the methods each object can run. An object is one item made from the blueprint. The Dog class below lists a name, an age, and a bark method. Rex and Bella are two objects made from it, each with its own name and age.

new builds the object. first.name = "Rex" fills one field of one object, and it leaves the other object untouched. Calling first.bark() runs the method on that object, so the greeting carries Rex's name. The program prints both barks and the two ages added together.

The Java Classes and Objects lesson builds more classes the same way.

class Dog {
  String name;
  int age;

  void bark() {
    System.out.println(name + " says woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog first = new Dog();
    first.name = "Rex";
    first.age = 3;
    Dog second = new Dog();
    second.name = "Bella";
    second.age = 5;
    first.bark();
    second.bark();
    System.out.println(first.age + second.age);
  }
}

Output:
Rex says woof
Bella says woof
8

23. What is a constructor?

A constructor builds an object and sets its fields in one step. It has the same name as the class and no return type. The Book constructor below takes a title and a page count, and stores both. Without it, every field would need its own line after new.

The program makes one book in one line: new Book("Dune", 412). The title and the pages are set before the object is ever used, so no book can exist half-built. this.title means the field of this object, as opposed to the parameter with the same name.

The Java Constructors lesson builds more objects in one step.

class Book {
  String title;
  int pages;

  Book(String title, int pages) {
    this.title = title;
    this.pages = pages;
  }
}

public class Main {
  public static void main(String[] args) {
    Book book = new Book("Dune", 412);
    System.out.println(book.title);
    System.out.println(book.pages);
  }
}

Output:
Dune
412

24. What do public, private, and static mean?

public, private, and static are three different promises. public means anyone can reach it. private means only its own class can reach it. static means it belongs to the class itself, not to any one object, so every object shares the same one.

The program below has a static counter. Each new Counter adds one to it, so after two objects the shared total is 2. It also has a final number: final means the value cannot change after it is set. Writing a new value into it fails to compile. The compiler refuses the assignment, because a final variable cannot take a new value.

The Java Modifiers lesson sets each word on more fields and methods.

class Counter {
  static int total = 0;
  final double pi = 3.14159;

  Counter() {
    total++;
  }
}

public class Main {
  public static void main(String[] args) {
    Counter a = new Counter();
    Counter b = new Counter();
    System.out.println(Counter.total);
    System.out.println(a.pi);
    System.out.println(b.pi);
  }
}

Output:
2
3.14159
3.14159

25. What is encapsulation, and why hide fields?

Encapsulation means hiding the inside of an object and offering methods instead. The balance of a bank account is private, so no outside code can set it to any number it likes. deposit is the only way money goes in, and getBalance is the only way the balance comes out. The field itself is out of reach.

The hiding is enforced by the compiler, not by politeness. The program below tries to write account.balance = 0 directly, and the compiler refuses with the error balance has private access in BankAccount. The right way in is the deposit method, which is the only code allowed to touch the field.

The Java Encapsulation lesson hides more fields the same way.

class BankAccount {
  private double balance = 50;

  void deposit(double amount) {
    balance += amount;
  }

  double getBalance() {
    return balance;
  }
}

public class Main {
  public static void main(String[] args) {
    BankAccount account = new BankAccount();
    account.balance = 0;
    System.out.println(account.getBalance());
  }
}

Output:
Main.java:16: error: balance has private access in BankAccount
    account.balance = 0;
           ^

26. What is inheritance?

Inheritance lets one class take over the fields and methods of another. Dog extends Animal, so a Dog can eat like any Animal and also bark like a Dog. The shared behaviour lives once, in Animal, instead of being copied into every animal class.

The program below makes a Dog and calls both methods on it. eat comes from Animal. bark comes from Dog. The Dog object carries both, because inheritance hands the parent's methods down to the child.

The Java Inheritance lesson grows a longer family tree.

class Animal {
  void eat() {
    System.out.println("eating");
  }
}

class Dog extends Animal {
  void bark() {
    System.out.println("woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.eat();
    dog.bark();
  }
}

Output:
eating
woof

27. What is polymorphism?

Polymorphism means one name with many shapes. An Animal variable can hold a Dog or a Cat, and the same call, speak(), gives a different answer for each. The variable's kind is Animal, but the object's kind decides which speak runs.

The program below stores a Dog and a Cat in two Animal variables. The first prints woof. The second prints meow. No if statement sorts them out: the object itself carries the answer. @Override marks a method as a replacement for the parent's version, so a spelling mistake there is a compile error instead of a silent new method.

The Java Polymorphism lesson calls more methods through parent variables. The Java Polymorphism in Depth lesson takes the idea further.

class Animal {
  String speak() {
    return "...";
  }
}

class Dog extends Animal {
  @Override
  String speak() {
    return "woof";
  }
}

class Cat extends Animal {
  @Override
  String speak() {
    return "meow";
  }
}

public class Main {
  public static void main(String[] args) {
    Animal first = new Dog();
    Animal second = new Cat();
    System.out.println(first.speak());
    System.out.println(second.speak());
  }
}

Output:
woof
meow

28. What is an abstract class?

An abstract class is a plan with a hole in it. It can hold real methods and real fields, and it can also declare methods with no body at all. Shape below has area() with no body, because a shape in general has no area. Only a real shape, like a circle, can answer that.

An abstract class cannot be built directly: new Shape() is a compile error. Its job is to be extended. Circle extends Shape and fills in area with the circle formula. The program stores the circle in a Shape variable and prints 12.56636, the area of a circle with radius 2.

The Java Abstraction lesson leaves more holes for subclasses to fill.

abstract class Shape {
  abstract double area();
}

class Circle extends Shape {
  double radius = 2;

  @Override
  double area() {
    return 3.14159 * radius * radius;
  }
}

public class Main {
  public static void main(String[] args) {
    Shape shape = new Circle();
    System.out.println(shape.area());
  }
}

Output:
12.56636

29. What is an interface?

An interface is a promise with no body at all. It lists methods a class must have, and says nothing about how they work. Drawable promises one method, draw(). Circle implements Drawable, so it must provide draw, and the compiler checks that it does.

A class can keep many promises at once. A class extends one parent, but it can implement several interfaces. The program below stores a Circle in a Drawable variable and calls draw on it. The variable knows only the promise, and the object keeps it.

The Java Interfaces lesson writes more promises the same way.

interface Drawable {
  void draw();
}

class Circle implements Drawable {
  @Override
  public void draw() {
    System.out.println("drawing a circle");
  }
}

public class Main {
  public static void main(String[] args) {
    Drawable d = new Circle();
    d.draw();
  }
}

Output:
drawing a circle

30. What is the difference between an abstract class and an interface?

An abstract class can hold state and finished methods. An interface holds only promises, plus small default methods. A class extends one abstract class, and it can implement many interfaces. That is the whole split: one parent with guts, many promises without.

The program below shows both at once. Car extends Vehicle, an abstract class with a name field and a finished start method, and it also implements Electric, an interface with one promise, charge. The car starts, reports four wheels, and charges. Each half of the split does its own job.

The Java Abstraction lesson and the Java Interfaces lesson each cover their own half.

abstract class Vehicle {
  String name = "car";

  void start() {
    System.out.println(name + " starts");
  }

  abstract int wheels();
}

interface Electric {
  void charge();
}

class Car extends Vehicle implements Electric {
  @Override
  int wheels() {
    return 4;
  }

  @Override
  public void charge() {
    System.out.println("charging");
  }
}

public class Main {
  public static void main(String[] args) {
    Car car = new Car();
    car.start();
    System.out.println(car.wheels());
    car.charge();
  }
}

Output:
car starts
4
charging

31. What is an enum?

An enum lists a fixed set of named values, and nothing else. Day holds the seven days of the week. A variable of kind Day can hold MONDAY or FRIDAY, and it cannot hold a made-up day like FUNDAY. The compiler checks that, so a typo is a compile error rather than a wrong value at run time.

Enums work with switch, and the program below switches on FRIDAY and prints weekday. Day.values() gives back all seven values, and the program prints their count. Enums are classes in disguise: each value is an object, and an enum can even carry fields and methods.

The Java Enums lesson lists more fixed sets. The Java Enums in Depth lesson takes enums further.

enum Day {
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {
  public static void main(String[] args) {
    Day today = Day.FRIDAY;
    System.out.println(today);
    switch (today) {
      case SATURDAY:
      case SUNDAY:
        System.out.println("weekend");
        break;
      default:
        System.out.println("weekday");
    }
    System.out.println(Day.values().length);
  }
}

Output:
FRIDAY
weekday
7

32. What is an ArrayList, and when do you use one?

An ArrayList is a list that grows. It holds values in order, lets you read any slot by number, and adds room as more values arrive. ArrayList<String> names makes a list of strings. The angle brackets name the kind it holds, and the compiler refuses any other kind.

The program below adds three names, reads the first, checks for Ben, removes him, and prints what is left. size counts the values. get reads one by position. contains asks whether a value is there. remove takes one out, and the later values slide down to fill the gap.

The Java ArrayList lesson grows more lists the same way.

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Ana");
    names.add("Ben");
    names.add("Cleo");
    System.out.println(names.size());
    System.out.println(names.get(0));
    System.out.println(names.contains("Ben"));
    names.remove("Ben");
    System.out.println(names.size());
    for (String name : names) {
      System.out.println(name);
    }
  }
}

Output:
3
Ana
true
2
Ana
Cleo

33. What is the difference between ArrayList and LinkedList?

Both hold a list in order, and both answer the same method calls. The difference is how they store the values. An ArrayList keeps them in one row, so reading slot 1 is instant. A LinkedList chains them as separate links, so removing the first link is cheap, and reading the middle means walking the chain.

The program below runs the same steps on both. Both print two for the second slot, and both print [two] after the first value is removed. The visible results match. The choice is about the work behind them: many reads favour the array, many insertions and removals at the ends favour the links.

The Java ArrayList in Depth lesson and the Java LinkedList in Depth lesson open up how each list stores its values.

import java.util.ArrayList;
import java.util.LinkedList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> array = new ArrayList<>();
    LinkedList<String> linked = new LinkedList<>();
    array.add("one");
    array.add("two");
    linked.add("one");
    linked.add("two");
    System.out.println(array.get(1));
    System.out.println(linked.get(1));
    array.remove(0);
    linked.removeFirst();
    System.out.println(array);
    System.out.println(linked);
  }
}

Output:
two
two
[two]
[two]

34. How does a HashMap work?

A HashMap stores pairs: a key and the value hung on it. ages.put("Ana", 9) hangs 9 on the key Ana. get("Ana") reads it back. Putting a second value on the same key replaces the first, so the map never holds two values for one key.

The program below puts two people in, then writes 10 over Ana's 9. The size stays 2, because replacing a value adds no new pair. get("Cleo") gives null, because Cleo has no key at all. containsKey asks whether a key is there before you read it.

The Java HashMap lesson maps more pairs. The Java equals and hashCode lesson explains the rule behind the keys: equal objects must share a hash code.

import java.util.HashMap;

public class Main {
  public static void main(String[] args) {
    HashMap<String, Integer> ages = new HashMap<>();
    ages.put("Ana", 9);
    ages.put("Ben", 12);
    ages.put("Ana", 10);
    System.out.println(ages.size());
    System.out.println(ages.get("Ana"));
    System.out.println(ages.get("Ben"));
    System.out.println(ages.containsKey("Cleo"));
    System.out.println(ages.get("Cleo"));
  }
}

Output:
2
10
12
false
null

35. What is a HashSet, and what is it for?

A HashSet holds values with no duplicates and no order. Adding red twice leaves one red. The set answers one question well: is this value already here? contains says yes or no, and it says it fast, even for a large set.

The program below adds red, blue, and red again. The size is 2, because the second red changed nothing. contains finds red and misses green. Removing blue leaves a size of 1. The set never promises an order, so the program prints sizes and answers, never the set itself.

The Java HashSet lesson keeps more sets the same way.

import java.util.HashSet;

public class Main {
  public static void main(String[] args) {
    HashSet<String> seen = new HashSet<>();
    seen.add("red");
    seen.add("blue");
    seen.add("red");
    System.out.println(seen.size());
    System.out.println(seen.contains("red"));
    System.out.println(seen.contains("green"));
    seen.remove("blue");
    System.out.println(seen.size());
  }
}

Output:
2
true
false
1

36. What does an Iterator do?

An Iterator walks through a collection one value at a time. next gives the next value. hasNext says whether one is left. The loop below takes each number in turn, and removes the even ones as it goes.

Removing during a walk needs the iterator's own remove. Removing from the list directly while walking it breaks the walk and throws an error. The program below ends with [1, 3]: the two even numbers are gone, and the walk finished cleanly.

The Java Iterator lesson walks more collections. The Java Iterating in Depth lesson covers the other ways to walk one.

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> nums = new ArrayList<>();
    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);
    Iterator<Integer> it = nums.iterator();
    while (it.hasNext()) {
      int n = it.next();
      if (n % 2 == 0) {
        it.remove();
      }
    }
    System.out.println(nums);
  }
}

Output:
[1, 3]

37. What are generics, and why use them?

Generics let one class work with many kinds. Box<T> is a box for any kind: T is a placeholder, and the real kind is chosen when the box is made. Box<String> holds words. Box<Integer> holds whole numbers. The compiler checks the kind, so a word can never land in the number box by mistake.

Before generics, a box held Object, and every value read out needed a cast that could fail at run time. Generics move that check to compile time, where a mistake is a red line instead of a crash. The program below fills a word box and a number box and prints both.

The Java Generic Classes lesson and the Java Generic Methods lesson write more placeholders. The Java Type Erasure lesson explains what the compiler does with them afterwards: the kinds are checked, then removed.

class Box<T> {
  private T value;

  void set(T value) {
    this.value = value;
  }

  T get() {
    return value;
  }
}

public class Main {
  public static void main(String[] args) {
    Box<String> word = new Box<>();
    word.set("hello");
    Box<Integer> count = new Box<>();
    count.set(42);
    System.out.println(word.get());
    System.out.println(count.get());
  }
}

Output:
hello
42

38. How do you sort objects with Comparable and Comparator?

Sorting needs a rule for which object comes first. Comparable puts the rule inside the class: Person compares by age, so Collections.sort lines people up youngest first. The rule is the class's own idea of order.

Comparator puts the rule outside the class. people.sort with a comparator by name lines the same people up alphabetically, without touching Person. One class can have one natural order, and as many comparators as anyone writes. The program below prints both orders.

The Java Sorting Objects with Comparable lesson and the Java Sorting with Comparators lesson each sort more lists.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Person implements Comparable<Person> {
  String name;
  int age;

  Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  @Override
  public int compareTo(Person other) {
    return this.age - other.age;
  }

  @Override
  public String toString() {
    return name + " " + age;
  }
}

public class Main {
  public static void main(String[] args) {
    ArrayList<Person> people = new ArrayList<>();
    people.add(new Person("Ben", 30));
    people.add(new Person("Ana", 9));
    people.add(new Person("Cleo", 25));
    Collections.sort(people);
    System.out.println(people);
    people.sort(Comparator.comparing(p -> p.name));
    System.out.println(people);
  }
}

Output:
[Ana 9, Cleo 25, Ben 30]
[Ana 9, Ben 30, Cleo 25]

39. What are streams, and what does a lambda do?

A stream is a conveyor belt for a collection. Values ride along it, and each step does one job: filter keeps some, map changes each one, and a final step gathers the result. The program below keeps the even numbers, doubles them, and collects [4, 8, 12]. The original list never changes.

A lambda is a small function with no name, written where it is used. n -> n * 2 means: take n, give back n times 2. filter and map each take a lambda that says what to do with one value. The program also stores a lambda in a variable and counts the numbers above 4, which is 2.

The Java Streams lesson runs more belts. The Java Lambda Expressions lesson writes more small functions. The Java Stream Operations lesson adds more steps, and the Java Functional Interfaces lesson names the kinds a lambda can be.

import java.util.List;
import java.util.function.Function;

public class Main {
  public static void main(String[] args) {
    List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
    List<Integer> doubled = nums.stream()
        .filter(n -> n % 2 == 0)
        .map(n -> n * 2)
        .toList();
    System.out.println(doubled);
    Function<String, Integer> length = s -> s.length();
    System.out.println(length.apply("hello"));
    System.out.println(nums.stream().filter(n -> n > 4).count());
  }
}

Output:
[4, 8, 12]
5
2

40. How does try and catch keep a program running?

An exception is an error that happens while a program runs. Dividing by zero throws an ArithmeticException, and an uncaught exception stops the program. try and catch keep it running: the risky lines sit in try, and catch runs when the error happens.

The program below divides 10 by 0 inside try. The catch prints the message, which is / by zero. finally runs either way, and prints done. The last line prints continues, which proves the program survived its own error.

The Java Exceptions lesson catches more errors the same way.

public class Main {
  public static void main(String[] args) {
    try {
      int n = 10 / 0;
      System.out.println(n);
    } catch (ArithmeticException e) {
      System.out.println("caught: " + e.getMessage());
    } finally {
      System.out.println("done");
    }
    System.out.println("continues");
  }
}

Output:
caught: / by zero
done
continues

41. What is the difference between throw and throws?

throw creates an exception. throws warns that a method can throw one. checkAge throws an IllegalArgumentException when the age is under 18. failChecked declares throws IOException in its header, which warns every caller that a checked failure can escape.

The two words work as a pair. throw is the act, inside the method body. throws is the warning, on the method header. The program below catches both: the age check prints its message, and the checked failure prints its own.

The Java Throw lesson covers both words in full.

import java.io.IOException;

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new IllegalArgumentException("too young: " + age);
    }
    System.out.println("old enough");
  }

  static void failChecked() throws IOException {
    throw new IOException("no file");
  }

  public static void main(String[] args) {
    try {
      checkAge(15);
    } catch (IllegalArgumentException e) {
      System.out.println("caught: " + e.getMessage());
    }
    try {
      failChecked();
    } catch (IOException e) {
      System.out.println("checked: " + e.getMessage());
    }
    checkAge(20);
  }
}

Output:
caught: too young: 15
checked: no file
old enough

42. What is the difference between a checked and an unchecked exception?

A checked exception must be faced before the code compiles. The compiler insists it is caught or declared, because the failure is a real possibility the caller must plan for: a missing file is the classic case. An unchecked exception needs no such promise, because it signals a programming mistake, like reading past the end of an array.

The program below shows both. Opening a missing file throws FileNotFoundException, which is checked, and the catch names it. Reading slot 5 of a two-slot array throws ArrayIndexOutOfBoundsException, which is unchecked. Both are caught, and the program prints continues at the end.

The Java Custom Exceptions lesson draws the line between the two kinds. The Java Exceptions lesson covers catching them.

import java.io.FileNotFoundException;
import java.io.FileReader;

public class Main {
  public static void main(String[] args) {
    try {
      new FileReader("missing.txt");
    } catch (FileNotFoundException e) {
      System.out.println("checked: " + e.getClass().getSimpleName());
    }
    try {
      int[] nums = new int[2];
      System.out.println(nums[5]);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("unchecked: " + e.getClass().getSimpleName());
    }
    System.out.println("continues");
  }
}

Output:
checked: FileNotFoundException
unchecked: ArrayIndexOutOfBoundsException
continues

43. What is try-with-resources, and how do you read a file?

Some objects must be closed after use, and a file is one of them. try-with-resources closes them for you: the object is made inside the brackets after try, and it is closed when the block ends, whether the block finished or failed. Nothing is left open by accident.

The program below writes its own file first, then reads it back. The writer writes two lines and closes. The reader reads the same two lines back. Because the program makes the file itself, it runs in any empty folder and prints the same two lines every time.

The Java Try with Resources lesson closes more objects the same way. The Java Reading Files lesson reads more files line by line.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
  public static void main(String[] args) throws IOException {
    try (BufferedWriter out = new BufferedWriter(new FileWriter("hello.txt"))) {
      out.write("Hello, file");
      out.newLine();
      out.write("Second line");
    }
    try (BufferedReader in = new BufferedReader(new FileReader("hello.txt"))) {
      System.out.println(in.readLine());
      System.out.println(in.readLine());
    }
  }
}

Output:
Hello, file
Second line

44. How do you run code on a second thread?

A thread is a second line of work inside one program. new Thread takes a small job, written as a lambda, and start sets it running beside the main thread. The two threads run at the same time, and the order their lines print in is not fixed.

The program below names its worker and waits for it. join pauses the main thread until the worker finishes, so worker always prints before main. Without join, the two prints could land in either order. Threads share the program's memory, so two threads writing one value at once need care, and the lessons named below cover that next.

The Java Threads and Runnable lesson starts more threads. The Java Executors and Futures lesson and the Java Synchronized and Locks lesson cover the shared-memory care.

public class Main {
  public static void main(String[] args) throws InterruptedException {
    Thread worker = new Thread(() -> {
      System.out.println("worker: " + Thread.currentThread().getName());
    }, "worker");
    worker.start();
    worker.join();
    System.out.println("main: done");
  }
}

Output:
worker: worker
main: done

45. How do you reverse a string?

Turn the string into a StringBuilder, reverse the builder, and read the string back out. One line does all three: new StringBuilder(s).reverse().toString(). The original string never changes, because strings cannot change. The method hands back a new string with the letters in reverse.

The program below reverses three words. hello becomes olleh. racecar stays racecar, because it reads the same both ways. Java becomes avaJ. A hand-written loop could do the same job, but the builder is the shorter answer in an interview.

The Java StringBuilder lesson reverses more strings. The Java String Methods lesson covers the methods that read a string without changing it.

public class Main {
  static String reverse(String s) {
    return new StringBuilder(s).reverse().toString();
  }

  public static void main(String[] args) {
    System.out.println(reverse("hello"));
    System.out.println(reverse("racecar"));
    System.out.println(reverse("Java"));
  }
}

Output:
olleh
racecar
avaJ

46. How do you find the largest number in an array?

Start by guessing the first number is the largest. Then walk the rest: whenever a number beats the current guess, it becomes the new guess. At the end of the walk, the guess is the largest number in the array. The walk touches each number once.

The program below finds 15 in {4, 9, 2, 15, 7}. The last line shows the shortcut for two numbers: Math.max(4, 9) gives 9. For a whole array, the loop is the answer, and the shortcut is only a helper inside it.

The Java Arrays lesson walks more arrays. The Java Math lesson covers the shortcuts.

public class Main {
  public static void main(String[] args) {
    int[] nums = {4, 9, 2, 15, 7};
    int biggest = nums[0];
    for (int n : nums) {
      if (n > biggest) {
        biggest = n;
      }
    }
    System.out.println(biggest);
    System.out.println(Math.max(4, 9));
  }
}

Output:
15
9

47. How do you spot a palindrome?

A palindrome is a word that spells the same in both directions. Lowercase the word first, so Racecar counts, then reverse it and compare the two. If the reversed word equals the original, the word is a palindrome.

The program below checks three words. racecar is true. Racecar is true, because the check lowercases it first. hello is false. The method returns a boolean, so the caller can use it straight in an if test.

The Java String Methods lesson covers the methods this check uses.

public class Main {
  static boolean isPalindrome(String word) {
    String lower = word.toLowerCase();
    return lower.equals(new StringBuilder(lower).reverse().toString());
  }

  public static void main(String[] args) {
    System.out.println(isPalindrome("racecar"));
    System.out.println(isPalindrome("Racecar"));
    System.out.println(isPalindrome("hello"));
  }
}

Output:
true
true
false

48. How do you count words in a sentence?

Split the sentence into words, then count them. split(" ") cuts the text at every space and hands back an array of words. The array's length is the word count. Counting one word, like fish, means walking the array and adding one for each match.

The program below splits "red fish blue fish red fish" into six words, and finds fish three times. The split needs care with extra spaces: two spaces in a row leave an empty word between them, and the count would be wrong. Trimming the sentence first avoids that.

The Java Splitting and Joining Text lesson splits more sentences.

public class Main {
  public static void main(String[] args) {
    String text = "red fish blue fish red fish";
    String[] words = text.split(" ");
    System.out.println(words.length);
    int fish = 0;
    for (String w : words) {
      if (w.equals("fish")) {
        fish++;
      }
    }
    System.out.println(fish);
  }
}

Output:
6
3

49. How do you print the Fibonacci numbers?

A Fibonacci number adds the two numbers that came before it. The list starts 0, 1, and then every next number is the sum of the last two. The program below keeps the last two numbers in two variables, prints the first, and steps both forward ten times.

The output is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. The loop runs ten times, and each pass prints one number. A recursive version could do the same job by calling itself, but the loop is faster, because the recursive version recomputes the same numbers many times.

The Java For Loop lesson builds the same list with a loop. The Java Recursion lesson builds it with a method that calls itself.

public class Main {
  public static void main(String[] args) {
    int a = 0;
    int b = 1;
    for (int i = 0; i < 10; i++) {
      System.out.print(a);
      if (i < 9) {
        System.out.print(", ");
      }
      int next = a + b;
      a = b;
      b = next;
    }
    System.out.println();
  }
}

Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

50. How do you write FizzBuzz?

FizzBuzz prints the numbers from 1 to 15 with a twist. A number divisible by 3 prints Fizz. A number divisible by 5 prints Buzz. A number divisible by both prints FizzBuzz. Every other number prints itself.

The order of the tests matters. The both-divisible test must come first: 15 is divisible by 3, so testing 3 first would print Fizz and never reach the FizzBuzz test. The program below tests 15 first, then 3, then 5, and prints the full fifteen lines.

The Java If...Else lesson and the Java For Loop lesson each cover their half of the program.

public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 15; i++) {
      if (i % 15 == 0) {
        System.out.println("FizzBuzz");
      } else if (i % 3 == 0) {
        System.out.println("Fizz");
      } else if (i % 5 == 0) {
        System.out.println("Buzz");
      } else {
        System.out.println(i);
      }
    }
  }
}

Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Questions readers ask

How do I work through this sheet in a week?

Work through one group each day, in order. Hide each answer, say yours out loud, then compare it with the page. Type out the programs and run them. Keep the last day for the six coding tasks and any question you missed. Short daily sessions beat one long night before the interview.

Must I memorise all fifty answers?

No. A few ideas carry the whole sheet: how objects hold state, how a list grows, how a map finds a value, and how an error is caught. Most questions here are one of those ideas in different clothes. If you can explain a class, sort a list, and trace a try block, the rest follows from those ideas.

Which Java version should I practise with?

Java 21. Every program on this page ran on Temurin OpenJDK 21.0.13, the long-term-support release. Earlier versions behave the same at this level, so the long-term-support release is the right one to practise with.

What does this sheet leave out?

Spring Boot, Android, and database access. The Java track has no lessons on those three yet, so this sheet skips them. Threads get one answer here, and the Advanced lessons named there cover executors, locks, and the rest. Every other answer names the lesson that teaches it.