TechSchool
Home / Interview questions / Java

Java interview questions

44 questions about Java with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.

Basics

1. What is an object in Java?

An object is an instance of a class. It has state and behavior. The state is stored in fields and the behavior is stored in methods.

Full lesson: Java basic syntax

2. What is a class in Java?

A class is a template for objects. It describes the state and behavior of its objects. Java code creates objects from the class.

Full lesson: Java basic syntax

3. How do you declare an ArrayList in Java?

Import the ArrayList class from java.util first. Then declare the type and the object name. The generic type must be a reference data type.

import java.util.ArrayList;
ArrayList<String> sites = new ArrayList<>();

Full lesson: Java arraylist

4. Which class is the parent of all Java classes?

The Object class is the parent of all classes. Every class inherits from Object. A class without an explicit parent inherits Object automatically.

public class Example extends Object { }

Full lesson: Java object class

5. What does the ArrayList add() method do?

The add() method inserts an element into the list. Without an index, it appends the element to the end. With an index, it inserts the element at that position.

sites.add("Google");
sites.add(1, "Wiki");

Full lesson: Java arraylist add

6. What does the ArrayList get() method return?

The get() method returns the element at the given index. The index starts at zero. An index out of range throws an IndexOutOfBoundsException.

String name = sites.get(0);

Full lesson: Java arraylist get

7. What does the ArrayList set() method return?

The set() method replaces the element at the given index. It returns the element that was at that index before. An index out of range throws an IndexOutOfBoundsException.

String old = sites.set(0, "Bing");

Full lesson: Java arraylist set

8. What does the ArrayList size() method return?

The size() method returns the number of elements in the list. The count includes all current elements. The count does not include empty slots.

int count = sites.size();

Full lesson: Java arraylist size

9. What does the ArrayList indexOf() method return?

The indexOf() method returns the index of the first match. It returns -1 when the element is absent. The search uses the equals() method.

int i = sites.indexOf("Google");

Full lesson: Java arraylist indexof

10. What does the ArrayList lastIndexOf() method return?

The lastIndexOf() method returns the index of the last match. It returns -1 when the element is absent. Use it to find a repeated element from the end.

int i = sites.lastIndexOf("Google");

Full lesson: Java arraylist lastindexof

11. How do you convert an ArrayList to a string?

Call the toString() method on the list. It returns the elements in square brackets. The elements are separated by a comma and a space.

System.out.println(sites.toString());

Full lesson: Java arraylist tostring

12. How do you remove elements from an ArrayList by a condition?

Use the removeIf() method with a predicate. The method removes every element that matches the predicate. It returns true when it removes at least one element.

sites.removeIf(s -> s.startsWith("G"));

Full lesson: Java arraylist removeif

13. How do you merge two arrays into one list?

Create a list from the first array with Arrays.asList(). Then call addAll() with the second array. Convert the list back to an array with toArray().

List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();

Full lesson: Arrays merge

14. How do you list the file names in a directory?

Call the list() method on a File object for the directory. It returns a String array of names. It returns null when the path is not a directory.

File dir = new File("C:/temp");
String[] names = dir.list();

Full lesson: Java file list

Intermediate

15. Why does list.add(5, "X") throw an exception on a list of size 3?

The add() method needs a valid index. A list of size 3 accepts index 0 to 3 only. Index 5 is out of range and throws IndexOutOfBoundsException.

ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add(5, "X"); // IndexOutOfBoundsException

Full lesson: Java arraylist add

16. What is the basic syntax of a Java class?

A class starts with the class keyword and a name. The class body goes between two braces.

public class Car {
  // fields and methods
}

Full lesson: Java basic syntax

17. How do you declare a variable in Java?

You write the type first, then the name. You can add an equal sign and a value to initialize it.

int count = 10;
String name = "Java";

Full lesson: Java variable types

18. What are the eight basic data types in Java?

The eight types are byte, short, int, long, float, double, char, and boolean. Each type has a fixed size and range.

Full lesson: Java basic datatypes

19. What is the difference between a public class and a private method?

A public class is visible to all other classes. A private method is visible only inside its own class.

public class Demo {
  private void helper() { }
}

Full lesson: Java modifier types

20. How do you create an object from a class?

You use the new keyword with the class name. This calls the class constructor.

Car myCar = new Car();

Full lesson: Java object classes

21. What does the ArrayList clear() method do?

The clear() method removes all elements from the list. The list becomes empty but still exists.

list.clear();

Full lesson: Java arraylist clear

22. What does the ArrayList addAll() method do?

The addAll() method adds all elements from another collection to the list. It returns true if the list changes.

list.addAll(otherList);

Full lesson: Java arraylist addall

23. What does the ArrayList remove() method do?

The remove() method deletes one element at a given index. It returns the removed element.

String removed = list.remove(2);

Full lesson: Java arraylist remove

24. How do you sort an ArrayList in natural order?

You call the sort() method with a comparator. Use Comparator.naturalOrder() for ascending order.

list.sort(Comparator.naturalOrder());

Full lesson: Java arraylist sort

25. What does the File toString() method return?

The toString() method returns the path string used to create the File object. It does not check if the file exists.

File f = new File("C:/test.txt");
System.out.println(f.toString());

Full lesson: Java file tostring

26. How do you get all files and subdirectories in a directory?

You call the listFiles() method on a File object that points to a directory. It returns an array of File objects.

File dir = new File("C:/temp");
File[] files = dir.listFiles();

Full lesson: Java file listfiles

27. What does the Object notify() method do?

The notify() method wakes up one thread that waits on the object monitor. The choice of thread is arbitrary.

synchronized (lock) {
  lock.notify();
}

Full lesson: Java object notify

28. What does the Object notifyAll() method do?

The notifyAll() method wakes up all threads that wait on the object monitor. They then compete for the lock.

synchronized (lock) {
  lock.notifyAll();
}

Full lesson: Java object notifyall

29. What happens if you call get() with an index equal to the list size?

The get() method throws an IndexOutOfBoundsException. Valid indices start at 0 and end at size minus 1.

list.get(list.size()); // throws exception

Full lesson: Java arraylist get

Common mistakes

30. What is a common mistake when you use clone() on an ArrayList?

The clone() method makes a shallow copy. Changes to mutable elements in the copy also affect the original list.

ArrayList<String> copy = (ArrayList<String>) list.clone();

Full lesson: Java arraylist clone

31. What does the String indexOf() method return?

The method returns the index of the first occurrence of a character or substring. It returns -1 if the character or substring is not found.

String s = "hello";
int i = s.indexOf('l');
System.out.println(i);

Full lesson: Java string indexof

32. How do you declare a local variable in a method?

You declare a local variable inside a method with a type and a name. You can also assign a value when you declare it.

public void exampleMethod() {
    int localVar = 10;
    System.out.println(localVar);
}

Full lesson: Java variable types

33. What is the default return value of the Object toString() method?

The default toString() method returns the class name, then an @ sign, then the hexadecimal hash code. This format is not easy to read.

Object obj = new Object();
System.out.println(obj.toString());

Full lesson: Java object tostring

34. How do you get the runtime class of an object?

You call the getClass() method on the object. The method returns a Class object that represents the runtime class.

String s = "hello";
System.out.println(s.getClass());

Full lesson: Java object getclass

35. What does the ArrayList clone() method do?

The clone() method copies an ArrayList. It makes a shallow copy, so the new list shares element references with the old list.

ArrayList<String> a = new ArrayList<>();
a.add("A");
ArrayList<String> b = (ArrayList<String>) a.clone();

Full lesson: Java arraylist clone

36. What does the Hashtable class store?

The Hashtable class stores key/value pairs in a hash table. It supports synchronization, unlike HashMap.

Hashtable<String, Integer> h = new Hashtable<>();
h.put("one", 1);
System.out.println(h.get("one"));

Full lesson: Java hashtable class

37. What does the Dictionary class do?

The Dictionary class stores key/value pairs, similar to a Map. It is an abstract class, so you cannot create a Dictionary object directly.

// Dictionary is abstract, so use a subclass like Hashtable
Dictionary<String, String> d = new Hashtable<>();
d.put("key", "value");

Full lesson: Java dictionary class

38. What happens if you call addAll() with a null collection?

The addAll() method throws a NullPointerException if the given collection is null. You must pass a non-null collection.

ArrayList<String> list = new ArrayList<>();
list.addAll(null); // throws NullPointerException

Full lesson: Java arraylist addall

39. What happens if you call remove() with an index that is out of range?

The remove() method throws an IndexOutOfBoundsException if the index is out of range. Check the list size before you call remove().

ArrayList<String> list = new ArrayList<>();
list.add("A");
list.remove(5); // throws IndexOutOfBoundsException

Full lesson: Java arraylist remove

40. What is a common mistake when you use indexOf() on a String?

A common mistake is to forget that indexOf() returns -1 when the character is not found. Always check for -1 before you use the result as an index.

String s = "hello";
int i = s.indexOf('z');
if (i != -1) {
    System.out.println(s.charAt(i));
}

Full lesson: Java string indexof

41. What is a common mistake when you declare a local variable?

A common mistake is to use a local variable before you assign a value to it. The compiler reports an error for an uninitialized local variable.

public void test() {
    int x;
    System.out.println(x); // compile error
}

Full lesson: Java variable types

42. What is a common mistake when you call toString() on an object?

A common mistake is to expect a useful string from the default toString() method. The default returns class name and hash code, so override toString() for readable output.

class Point {
    int x = 1, y = 2;
    public String toString() { return "(" + x + "," + y + ")"; }
}

Full lesson: Java object tostring

43. What is a common mistake when you use getClass()?

A common mistake is to call getClass() on a null reference. This throws a NullPointerException because there is no object.

Object obj = null;
System.out.println(obj.getClass()); // throws NullPointerException

Full lesson: Java object getclass

44. What is a common mistake when you use Hashtable?

A common mistake is to store null keys or null values. Hashtable does not permit null keys or null values and throws a NullPointerException.

Hashtable<String, String> h = new Hashtable<>();
h.put(null, "value"); // throws NullPointerException

Full lesson: Java hashtable class

More on TechSchool
See the Java cheat sheet Python JavaScript TypeScript HTML CSS React Vue 3 Node.js PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures