50+ Important Java Interview Questions and Answers to Know

how to answer Java Interview Questions
Summary:

Study these essential Java interview questions and answers to prepare for upcoming technical interviews and land the Java job you want.

Need to interview a Java developer for a freelance project or job? Here are 37 essential Java interview questions and answers provided by some of our top Java experts here at Arc.

Although technical interviews can’t gauge how well a candidate would perform on a real-life project, this is still an integral part of the hiring process. Here are some Java interview questions that you can ask a developer to evaluate their understanding of the language.

Looking to hire the best remote developers? Explore HireAI to see how you can:

⚡️ Get instant candidate matches without searching
⚡️ Identify top applicants from our network of 300,000+ devs with no manual screening
⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

Basic Java Interview Questions

1. What’s the difference between StringStringBuffer, and StringBuilder?

String is an immutable class. In older JDKs the recommendation when programmatically building a String was to use StringBuffer since this was optimized to concatenate multiple Strings together.

However, the methods StringBuffer were marked as synchronized, which meant that there was a performance penalty, hence StringBuilder was introduced to provide a non-synchronized way to efficiently concatenate and modify Strings.

2. How do you run a Java application on the command line and set the classpath with multiple jars?

This is one of those Java interview questions where some people will be thinking what!? But, I’ve met a lot of Java developers who’ve not run a Java application outside of an IDE for years.

java -cp /dev/myapp.jar:/dev/mydependency.jar com.arc.MyApp

3. What is the difference between finalfinalize and finally?

final is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.

4. How does Garbage Collection prevent a Java application from going out of memory?

This is a tricky Java interview question… it doesn’t have to be!

Garbage Collection simply cleans up unused memory when an object goes out of scope and is no longer needed. However, an application could create a huge number of large objects that causes an OutOfMemoryError.

5. What’s the difference between a ClassNotFoundException and NoClassDefFoundError?

A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason the class could not be turned into a Class definition.

A common cause is an exception being thrown in static initialization blocks.


Check out our entire set of software development interview questions to help you hire the best developers you possibly can.

If you’re a developer, familiarize yourself with the non-technical interview questions commonly asked in the first round by HR recruiters and the questions to ask your interviewer!

Arc is the radically different remote job search platform for developers where companies apply to you. We’ll feature you to great global startups and tech companies hiring remotely so you can land a great remote job in 14 days. We make it easier than ever for software developers and engineers to find great remote jobs. Sign up today and get started.


6. Why isn’t String‘s .length() accurate?

It isn’t accurate because it will only account for the number of characters within the String. In other words, it will fail to account for code points outside of what is called the BMP (Basic Multilingual Plane), that is, code points with a value of U+10000 or greater.

The reason is historical: when Java was first defined, one of its goal was to treat all text as Unicode; but at this time, Unicode did not define code points outside of the BMP. By the time Unicode defined such code points, it was too late for char to be changed.

This means that code points outside the BMP are represented with two chars in Java, in what is called a surrogate pair. Technically, a char in Java is a UTF-16 code unit.

The correct way to count the real numbers of characters within a String, i.e. the number of code points, is either:

someString.codePointCount(0, someString.length())

or, with Java 8:

someString.codePoints().count()

7. Given two double values d1d2, why isn’t it reliable to test their equality using:

d1 == d2

Because of Double.NaN (literally: “Not a Number”).

This code:

final double d1 = Double.NaN;
final double d2 = Double.NaN;

System.out.println(d1 == d2);

will print false.

The most accurate way to tell whether two double values are equal to one another is to use Double.compare() and test against 0, as in:

System.out.println(Double.compare(d1, d2) == 0);

8. What is the problem with this code:

final byte[] bytes = someString.getBytes();

There are, in fact, two problems:

  • the code relies on the default Charset of the JVM;
  • it supposes that this default Charset can handle all characters.

While the second problem is rarely a concern, the first certainly is a concern.

For instance, in most Windows installations, the default charset is CP1252; but on Linux installations, the default charset will be UTF-8.

As such, such a simple string as “é” will give a different result for this operation depending on whether this code is run on Windows or Linux.

The solution is to always specify a Charset, as in, for instance:

final byte[] bytes = someString.getBytes(StandardCharsets.UTF_8);

The what is the problem with this code? question is one of the most popular Java interview questions, but it’s not necessarily going to be this one above, of course. Be prepared to do some detective work to identify the issue.

Also, keep in mind: while the problem may be exception handling, method overloading, an access specifier issue, or something else, it could also be nothing at all! This is one of those trick Java interview questions where the answer will rely on your gut that everything is perfect with the code already.

9. What is the JIT?

The JIT is the JVM’s mechanism by which it can optimize code at runtime.

JIT means Just In Time. It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc.

The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.

(On a more advanced note: the JIT is such a complex piece of machinery that it makes it complicated to do accurate performance benchmarks for JVM code; this is why such frameworks as JMH exist.)

10. How do you make this code print 0.5 instead of 0?

This code:

final double d = 1 / 2;

System.out.println(d);

prints 0. Why? How do you make this code print 0.5 instead?

The problem here is that this expression:

1 / 2

has integer literals on both sides of the operator: 1 and 2. As a consequence, an integer division will be performed, and the result of 1 divided by 2 in an integer division is 0.

In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:

final double d = 1 / 2.0;

or:

final double d = 1.0 / 2;

11. What is the inferred type of the method reference System.out::println?

In this code:

IntStream.range(0, 10).forEach(System.out::println);

what is the inferred type of the method reference System.out::println?

It is an IntConsumer.

IntStream.range(0, 10) returns an IntStream, and IntStream defines a .forEach() method accepting an IntConsumer as an argument, whose prototype is:

void accept(int value);

System.out is a PrintStream, and a PrintStream has a method named println which takes an int as an argument and returns void. This matches the signature of an IntConsumer, hence the result.

12. What is the problem with this code?

final Path path = Paths.get(...);

Files.lines(path).forEach(System.out::println);

The problem is that the Stream returned by Files.lines() is not closed.

This should be used instead:

try (
    final Stream<String> stream = Files.lines(path);
) {
    stream.forEach(System.out::println);
}

Stream extends BaseStream, and BaseStream extends AutoCloseable. While this has no influence on streams you obtain from collections for instance, the stream returned by Files.lines() is I/O bound. Neglecting to close it correctly may lead to a resource leak if an error occurs while processing the stream.

13. What will be the contents of a list after a given operation and why?

Consider the following piece of code:
(Question provided by Francis Galiegue)

final List<Integer> list = new ArrayList<>();

list.add(1);
list.add(2);
list.add(3);

list.remove(2);

What will be the contents of the list after this operation and why?

The contents will be:

[ 1, 2 ]

The reason is that there are two removal operations on a List:

  • remove(int index)
  • remove(Object obj)

The JVM will always select the most specific overload of a method; and here we pass an int as an argument, the code therefore removes the element at index 2.

To remove the _element_ 2 from the list, the following needs to be written:

list.remove(Integer.valueOf(2));

14. Write a function to detect if two strings are anagrams (for example, SAVE and VASE)

This is my go-to first interview question. It helps me gauge a candidate’s ability to understand a problem and write an algorithm to solve it.

If someone has not solved the problem before, I expect to see some code with loops and if/then’s. Maybe some HashMaps. I look for the ability to break down the problem to see what you need to check, what the edge cases are, and whether the code meets those criteria.

The naive solution is often to loop through the letters of the first string and see if they’re all in the second string. The next thing to look for is that the candidate should also do that in reverse too (check string 1 for string 2’s letters)? The next thing to look for is, what about strings with duplicate letters, like VASES?

If you can realize that these are all required and create a functional, non-ridiculous solution, I am happy.

Of course, one can solve it trivially by sorting and comparing both strings. If someone catches this right away, they usually have seen the problem before. But that’s a good sign that someone cares enough to do prep work. Then we can tackle a harder problem.

public static boolean isAcronym(String s1, String s2) {

    if (s1.length() != s2.length()) return false;

    HashMap<Character, Integer> charCounts = new HashMap<>();

    // Calculate chracter counts

    for (int i = 0; i < s1.length(); i++) {
      if (charCounts.containsKey(s1.charAt(i))) {
           charCounts.put(s1.charAt(i), charCounts.get(s1.charAt(i)) + 1);
      } else {
           charCounts.put(s1.charAt(i), 1);
      }
    }

    // Compare counts with characters in s2

    for (int i = 0; i < s2.length(); i++) {
        if (charCounts.containsKey(s2.charAt(i))) {
           charCounts.put(s2.charAt(i), charCounts.get(s2.charAt(i)) - 1);
        } else {
           return false;
        }
    }

    // Check all letters matched
    for (int count : charCounts.values()) {
        if (count != 0) return false;
    }

    return true;
}

The details of the implementation are not important; what’s important is that the candidate understands what they need to do, and also understands why their solution works or doesn’t work. If the candidate can demonstrate this, they’re on the right track.

Here is one way to implement a better solution, comparing sorted strings:

public static boolean isAcronymMoreBetter(String s1, String s2) {
    char[] s1Chars = s1.toCharArray();
    char[] s2Chars = s2.toCharArray();
    Arrays.sort(s1Chars);
    Arrays.sort(s2Chars);
    return Arrays.equals(s1Chars, s2Chars);
}

15. What is the contract between equals and hashCode of an object?

The only obligation is that for any objects o1 and o2 then if o1.equals(o2) is true then o1.hashCode() == o2.hashCode() is true.

Note that this relationship goes only one way: for any o1, o2 of some class C, where none of o1 and o2 are null, then it can happen that o1.hashCode() == o2.hashCode() is true BUT o1.equals(o2) is false.

16. Can an enum be extended?

No. Enum types are final by design.

17. How threadsafe is enum in Java?

Creation of an enum is guaranteed to be threadsafe. However, the methods on an enum type are not necessarily threadsafe

18. How does the JVM handle storing local variables vs storing objects?

Objects are stored on the heap. Variables are a reference to the object.

Local variables are stored on the stack.

19. Identify the problem in the below Java code:

public class Foo {
    public Foo() {
        doSomething();
    }

    public void doSomething() {
        System.out.println("do something acceptable");
    }
}

public class Bar extends Foo {
    public void doSomething() {
        System.out.println("yolo");
        Zoom zoom = new Zoom(this);
    }
}

A classic example of escaping references.

When an object of Bar is created, the super constructor in Foo gets called first, which in turn calls the ‘overridden’ doSomething method.

The doSomething method passes the this instance to the class ZoomZoom now can use the ‘this‘ instance before it is created entirely. BAD!!!

20. When do you use volatile variables?

When a member variable is accessed by multiple threads and want the value of a volatile field to be visible to all readers (other threads in particular) after a write operation completes on it.

More Important Basic Questions for Java Developers

Keep in mind that, although Java is already an object-oriented programming language, you may want to ask questions about object-oriented programming that are more theoretical, conceptual, and outside general Java programming.

Consider including the following additional core Java interview questions on OOP:

  • What are classes / objects / abstractions / inheritances in object-oriented programming?
  • Can you name the 5 SOLID object-oriented programming design principles?
  • How do method overloading and method overriding work in OOP or Java?
  • What is an abstract class in Java?

Intermediate Java Interview Questions

21. Why do you need to use synchronized methods or blocks?

If threads are being used and a number of threads have to go through a synchronized section of code, only one of them may be executed at a time. This is used to make sure shared variables are not updated by multiple threads.

22. What is the difference between HashMap and ConcurrentHashMap?

ConcurrentHashMap is thread-safe; that is the code can be accessed by single thread at a time while HashMap is not thread-safe. ConcurrentHashMap does not allow NULL keys while HashMap allows it.

23. When do you need to override the equals and hashCode methods in Java?

By defining equals() and hashCode() consistently, the candidate can improve the usability of classes as keys in hash-based collections such as HashMap.

24. What is a Service?

A service is a function that is well-defined, self-contained, and does not depend on the context or state of other services.

25. What is a good use case of calling System.gc()?

One may call System.gc() when profiling an application to search for possible memory leaks. All the profilers call this method just before taking a memory snapshot.

26. What is the marker interface in Java?

The marker interface in Java is an interface with no field or methods. In other words, it an empty interface in java is called a marker interface. An example of a marker interface is a Serializable, Clonable, and Remote interface. These are used to indicate something to the compiler or JVM.

27. How are Annotations better than Marker Interfaces?

Annotations allow one to achieve the same purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful, too, letting programmers pass more sophisticated information to classes that “consume” it.

28. What are checked and unchecked exceptions? When do you use them?

checked exception is an exception that must be catch, they are checked by the compiler. An unchecked exception is mostly runtime exception, and is not required to be catch. In general, use checked exception when the situation is recoverable (retry, display reasonable error message).

29. int a = 1L; won’t compile and int b = 0; b += 1L; compiles fine. Why?

When += is used, that’s a compound statement and the compiler internally casts it. Whereas in the first case, the compiler straightaway shouts at you since it is a direct statement.

Compiler behavior and statement types can be confusing, so questions like this will test a candidate’s grasp of these concepts.

30. Why aren’t you allowed to extend more than one class in Java but are allowed to implement multiple interfaces?

Extending classes may cause ambiguity problems. On the other hand, in terms of interfaces, the single method implementation in one class can serve more than one interface.

Other Intermediate Interview Questions for Java Developers

Be sure you ask about multithreading, as it’s one of Java’s most important features. Here are a few Java multithreading questions you want to ask:

  • How does multithreading work?
  • How to implement a thread in Java?
  • How to create daemon threads?
  • What is thread starvation?
  • What is the ExecutorService interface and how does it work?

You can also explore HireAI to skip the line and:

⚡️ Get instant candidate matches without searching
⚡️ Identify top applicants from our network of 250,000+ devs with no manual screening
⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

Advanced Java Interview Questions for Experienced Developers

31. Why doesn’t the following code generate a NullPointerException even when the instance is null?

Test t = null;
t.someMethod();

 public static void someMethod() {
  ...
}

There is no need for an instance while invoking a static member or method since static members belong to a class rather than an instance.

A null reference may be used to access a class (static) variable without causing an exception.

32. Look at the below code. Why is the code printing true in the second and false in the first case?

public class Test
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.out.println(a == b);

        Integer c = 100, d = 100;
        System.out.println(c == d);
    }
}

outputs:

false
true

JVM’s cache behavior can be confusing, so this question tests that concept. The second output is true as we are comparing the references because the JVM tries to save memory when the Integer falls within a range (from -128 to 127).

At point 2, no new reference of type Integer is created for ‘d’. Instead of creating a new object for the Integer type reference variable ‘d’, it is only assigned with a previously created object referenced by ‘c’. All of these are done by JVM.

33. How do you check if the given two strings below are anagrams or not?

String s1="home";
String s2="mohe";
boolean result = new String(Arrays.sort(s1.toCharArray()))
                  .equals(new String(Arrays.sort(s2.toCharArray())));

34. How do you reverse String("Java Programming") without using Iteration and Recursion?

System.out.println("reverse = " + new StringBuilder(givenString).reverse());

35. Give real-world examples of when to use an ArrayList and when to use LinkedList.

ArrayList is preferred when there are more get(int), or when search operations need to be performed as every search operation runtime is O(1).

If an application requires more insert(int) and delete(int) operations, then LinkedList is preferred, as LinkedList does not need to maintain back and forth to preserve continued indices as arraylist does. Overall this question tests the proper usage of collections.

36. What is the difference between an Iterator and a ListIterator?

This question tests the proper usage of collection iterators. One can only use ListIterator to traverse Lists, and cannot traverse a Set using ListIterator.

What’s more, one can only traverse in a forward direction using Iterators. Using ListIterator, one can traverse a List in both the directions (forward and backward).

One cannot obtain indexes while using Iterator. Indexes can be obtained at any point of time while traversing a list using ListIterator. The methods nextIndex() and previousIndex() are used for this purpose.

37. What is the advantage of a generic collection?

They enable stronger type checks at compile time.

A Java compiler applies strong type checking to generic code, and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

Conclusion

Hopefully, you’ve found these interview questions useful when vetting Java developers.

Keep in mind that the technical interview is just one portion of the hiring process. Whether you’re hiring freelance or full-time Java developers, you also want to evaluate their soft skills like communication, problem-solving, time management, and more.

You can also explore HireAI to skip the line and:

⚡️ Get instant candidate matches without searching
⚡️ Identify top applicants from our network of 250,000+ devs with no manual screening
⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

Written by
Arc Team
Join the discussion