Java Interview Questions

Interview Questions for Java Programmers

When discussing preparation for a Java programming interview, the focus is typically on the interviewee. Candidates want to know what types of questions to expect so that they can best prepare. Yet the point at issue remains – what type of java interview questions does an employer ask potential candidates in order to best evaluate their skills?

In a software development house, regardless of whether the java programming language or even object oriented programming is standard, coming up with programming questions and answers is straightforward. It is easy to employ Google, for example, to search for language syntax to help with writing the core java interview. However, what happens in cases where (or when) the company needs to hire a contractor for a simple project? Or, similarly, the existing team is non-technical and they are expanding to include their own in-house software group?

Before starting, here is a quick definition of the term Java that should help you if you are not familiar with this language:

Java is a high-level programming language developed by Sun Microsystems. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications.

The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being more strict than C++, meaning variables and functions must be explicitly defined. This means Java source code may produce errors or “exceptions” more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types.

Christensson, P., Java Definition, techterms.com

Java defines a String class to represent arrays of characters. Answer the following questions:

A constructor initializes an object when it is created. However, constructors have no explicit return type.

Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Could you name some Java frameworks?

This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language.
During the interview, the interviewed candidate must mention at least three Java frameworks among this list:

  • JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
  • GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
  • Struts
  • Hibernate
  • Grails
  • Play!
  • Vaadin
  • Maven

Mixed-level Programming Interview Questions

Java defines a String class to represent arrays of characters. Answer the following questions:

– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical?
– If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?

1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); } 

Will this work? If not, what changes would be required in order to output the desired string?

2/ The String class has more than one Comparator. Consider the following code:

public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); } 

– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical?
– If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?

3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?

Rationale

Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.   

Correct answers

  1. No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
  2. The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.

    In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.

  3. The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.

  4. For example:

    string x = “main string”;
    string y = “virtual machine”;
    string z = “main string”; 

    All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.

What are the differences between Stack memory and Heap space?

Rationale

In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.

Correct answers

Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.

Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.

Very Bad

Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.

Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?

Rationale

In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.

Correct answers

A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.

A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.

Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.

Bonus

There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.

Very Bad

The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.

Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?

Rationale

The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.

Correct answers

Array

  1. Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
  2. Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
  3. The size of an array is set when it is created.
  4. The random access of an element in an array is very efficient.
  5. Arrays are most suitable for a fixed-length collections of elements.
  6. All of the elements are of the same type, for example:

int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5}; 

Both of these Arrays contain five integers.

Vector

Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.

  1. Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
  2. The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
  3. A List relies on the methods from Collections for sorting, such as Collections.sort().
  4. The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
  5. Lists can store objects of mixed type, for example:

List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”); 

Bonus

Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.

Very Bad

Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.

Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?

Rationale

While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.

Correct answers

An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:

public interface CheckerBoard {
    public void setSize(int rowCount, int columnCount); 
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {} 

In this example, the ChessGame interface inherits from both CheckerBoard and Game.

Very Bad

If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.

What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?

Rationale

No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.

Correct answers

The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.

Very Bad

The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.

What are final methods and classes? Will an abstract class support final methods?

Rationale

The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.

Correct answers

A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.

Very Bad

If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.

Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.

Rationale

Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.

Correct answers

What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?

public class JavaInterviewClass implements Runnable {
    public void run() {
    System.out.println(“My example public class prints this line from a thread.”);
    }
}    
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start(); 
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
    public void run() {
    System.out.println(“My example public class extends the Thread class.”);
    }
} 
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start(); 

Bonus

While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.

Very Bad

If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.

Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?

Rationale

Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.

Correct answers

  1. An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
  2. yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
  3. sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
  4. join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.

Very Bad

Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.

Conclusion

The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.

Java defines a String class to represent arrays of characters. Answer the following questions:

A constructor initializes an object when it is created. However, constructors have no explicit return type.

Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Could you name some Java frameworks?

This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language.
During the interview, the interviewed candidate must mention at least three Java frameworks among this list:

  • JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
  • GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
  • Struts
  • Hibernate
  • Grails
  • Play!
  • Vaadin
  • Maven

Mixed-level Programming Interview Questions

Java defines a String class to represent arrays of characters. Answer the following questions: