Low Orbit Flux Logo 2 F

Java Interview Questions

We are going to cover common Java interview questions and help give you an idea of what to expect. These should help you answer these questions quickly and confidently without having to come up with an answer right on the spot.

Part 1 - Java Interview Questions: How To Do Well In Your Next Java Job Interview

To this day, Java remains one of the most lucrative options for people that want to break into the software development field. Even with the increase in popularity in languages such as Python and Swift, the demand for Java still remains dominant because not only is it one of the most powerful languages, it also provides the backbone for most applications that are made for the world’s most popular mobile operating system — Android.

Not to mention that Java developers in the United States stand to make an impressive $105,801 per year not including vested stock options and bonuses. So if you are a new developer preparing for your first Java technical job interview, here are some of the most common questions and how you can answer them in a way that will impress the recruiter.

Why Do You Choose Java Over Any Other Language?

In order to get the answer to the question right, you have to pinpoint a feature of Java and make clear to your recruiter that it is something that you value for your own projects. You can mention, as we stated earlier, that you are passionate about creating native applications for Android so Java is a natural choice for you. You can also mention that you like that Java has a robust developer community and has greater high level concurrency compared to older languages like C++.

What Are Your Favorite Features of Java?

Just like the previous question, this one is subjective and there really aren’t any wrong answers just as long as the features that you mention are features that you can expound upon in a way that is technically correct. You can mention that you appreciate the simplicity of Java, it is a language that is not too difficult to learn but does not have type inference like other simple programming languages like Python or Swift, this way you can avoid semantic issues when typecasting.

What Java IDEs Do You Prefer Working With?

Once again, this question is subjective and you do not have to worry about getting this answer wrong. The reason why recruiters often ask subjective questions that have no right or wrong answers like this is they want to gauge how comfortable you are with your answer.

For these subjective questions, getting the answer right is not as important as delivering your answer confidently and with poise. They are, afterall, trained to tell whether an applicant is pulling out a random answer that may not exactly be sincere, or whether you really do enjoy using a particular IDE like Netbeans, Eclipse, or IntelliJ.

Specify Different Ways You Can Instantiate a Java Object?

Unlike the first three questions, this one is more technical and does in fact have right and wrong answers. To make your answer concise, you most likely do not have to provide every single method to instantiate an object in Java, but the most common 3 ways to do it would suffice. For pedagogical sense, you can answer by saying:

What is The Difference Between An Abstract Class and an Interface?

Abstraction and inheritance are very important concepts in Java so your recruiter will most likely want to find out whether you know the difference between the two concepts. The recruiter will often start by asking you what the difference between an abstract class and an interface is.

Answer by saying that an abstract class is extended, not inherited, and you can have fields and constructors defined in an abstract class. An interface, on the other hand, is implemented rather than just extended and it cannot have constructors or data fields. An abstract class also cannot support more than one implementation while interfaces can.

What is The Importance of Setting a Global Variable Private?

To answer this question, tell your recruiter that setting a global variable private is important because global variables can affect the logical correctness and function of all the methods that have access to it. If it is not set to private, a method outside of the class that it is in can manipulate it explicitly and ruin the logic of the methods that have an actual use for it.

Instead, these must be set to private and its value must only be manipulated by methods that actually have logic in place to set to make sure that the value that is stored in the variable is actually acceptable.

Why Would You Choose To Create SET Methods When You Can Specify Fields in a Constructor?

Even though you can specify the value of certain fields of a class using an overloaded constructor, you cannot change the value of a field if it is in a constructor. You can only do this using a method that has access to that variable, or a setter method.

It would always help if you cite a specific example to your interviewer. If you create a student class, for example, and a boolean variable “graduated” is one of its fields, it would not make sense to define the value of this field in a constructor as false because you could not ever change it to true even when the student has graduated.

What is Inheritance In Java?

Keep your answer to this one simple because a simple but precise answer will make your recruiter know that you are confident with the information that you have; inheritance in Java is simply the way for one class to inherit something from another class.

Classes Doctor or Lawyer can inherit the specifics of an Employee interface in that it must have a salary, it must have a set number of working hours, and it needs to have a first name and last name.

What is Abstraction in Java?

To keep it simple, answer this by saying that abstraction in Java is a way to achieve variation in one class from a class that it extends. Once again, an example would be appreciation by your interviewer.

In Java, you cannot instantiate an Employee object if it is abstract, but you can instantiate a Doctor or a Lawyer object that extends the Employee abstract class. If you specify that an Employee has to have a catchphrase, both the Doctor and Lawyer classes will be able to implement such a method. Whereas the Employee abstract class will simply indicate that there is a catphrase method, the doctor.getCatchphrase(); method can yield “time to get you feeling better” while the lawyer.getCatchphrase(); would yield “I’ll see you in court”.

Why Do You Believe You Can Become a Good Java Developer?

This is often asked at the end of a lot of Java interviews. You have to know what the qualities of a good Java developer are and which of those qualities play to your strength. A Java developer needs to be inquisitive, patient, have a passion for problem solving, and has decent arithmetic skills. Expound to your interviewer why you have those qualities and cite specific instances in your professional or academic career wherein you exhibited those traits.

With these tips in mind, there is no doubt that you will do very well in your next Java interview. Remember that not only does the content of your answer matter, but the confidence by which they are delivered is also very important. Practice in front of a mirror or with a colleague and you will absolutely nail that interview!

Part 2 - Java Interview Questions

What is Polymorphism? Define and provide examples of both types.

Polymorphism is the concept that an object or method can have multiple implementations depending on the circumstances. There are two types of polymorphism observed in computer science: compile-time and runtime.

Compile-time (also known as static) polymorphism uses static binding, which occurs during compile-time. When the code is compiled, the compiler knows which method calls are linked to which methods. A prime example of compile-time polymorphism is method overloading. Method overloading occurs when there are multiple functions with the same name, allowing a function to have multiple implementations depending on the circumstances. These functions must differ in at least one of three categories: 1) Parameter type, 2) Number of parameters, 3) Parameter order.

To demonstrate method overloading, I will use the Point class below. The example will use parameters of different types.

Java Interview Questions Example1

Parameter Type Example:

As you can see, there are two functions named divdeX with different type parameters. One performs integer division and one performs double division.

Java Interview Questions Example2

Here is how they are used. Note that in the first call, a double (2.0) is used as the argument, and in the second call, an integer (2) is used as the argument.

Java Interview Questions Example3

Here is the output of what is printed. As you can see, the functions called in both cases had the same name, but the functions performed differently based on the type of the argument.

Java Interview Questions Example4

Runtime (also known as dynamic) polymorphism occurs when the compiler cannot tell which method to use during compilation, and dynamic binding is used instead. Dynamic binding occurs during runtime, hence the name runtime polymorphism. The prime example of runtime polymorphism is method overriding. This occurs when a subclass has a method with the same name as a method in the superclass.

To demonstrate method overriding, I will use the Fruit superclass and Apple subclass as an example. Both have the method printType.

Java Interview Questions Example5

As you can see, the outputs differ even though the functions have the same name, and both objects are type Fruit.

Java Interview Questions Example6

What is the difference between the Heap and the Stack? Give an example of what might be stored in each.

The Heap and the Stack are both forms of memory in Java. The primary differences between the two are:

These main differences should give you an idea of what types of data might be stored in the heap and the stack. For example, if you create an object, it is stored in the heap. The reference variable that points to the object will be stored in the stack.

For another example, consider integer arrays vs integers. Integers are primitive types, so they are stored in the stack. Integer arrays are reference types, so their values are stored in the heap. When both are passed into a function, the integer array’s reference variable is passed, so the function can access the array values in the heap. On the other hand, the value of the integer is what is passed into the function, so modifying the argument will only modify a copy of the value. This is the reason that functions can modify integer array values when they are inputted as arguments, but not integers themselves. See the example below for clarity.

Example Code:


void incrementIntArray(int[] x) {x[0] += 1; }
void incrementInt(int x) {x += 1; }

int[] xArray = new int[] {4};
int x = 4;

incrementIntArray(xArray);
incrementInt(x);

At this point, x[0] will equal 5 while x will still equal 4.

What are static methods and why are they sometimes NOT considered good practice for O.O programming?

Declaring a method as static signifies that the method doesn’t rely on any non-static components of the class it is in, and it remains constant over all instances of said class. In certain cases, this can be beneficial, since being unable to use non-static components reduces the scope of the method and room for error.

However, static methods cannot be used with abstract classes and interfaces, as they can only define non-static methods. Because of this, static methods do not fit in well with one of the most important O.O programming techniques, inheritance.

Additionally, static methods cannot make use of super(), so they are unable to be overridden. This can lead to a lot of confusion, especially for other programmers looking over your code. This also means that static methods do not support polymorphism, another key technique in O.O programming.

Nevertheless, Java is not a purely O.O programming language, so there are definitely still cases where static methods can and should be used.

What is multithreading and when are synchronized blocks necessary?

Multithreading is when a Java program has two or more processes running at the same time. These processes are called threads, and each runs parallel and independent to each other during multithreading. This means that if one thread throws an exception, the other threads won’t be affected. Each thread also has its own stack, but all threads share the same heap space. The advantages of multithreading include but are not limited to: maximizing CPU, running more than one task at once, and making tasks much easier.

Since threads run asynchronously and use the same heap for allocated storage, issues may arise if two threads attempt to read/write the same data. To prevent these issues, synchronized blocks are needed. Synchronized blocks prevent more than one thread from running the code contained within the block at a time. So, when one thread reaches a synchronized block, all other threads must wait until the first thread finishes to run the code within the block.

What is the difference between an abstract class and an interface? When would you use one over the other?

Abstract classes and interfaces are both used for inheritance, however, there are many differences between the two. I’ve listed the key differences below:

These differences give many reasons to use one over the other. An example for using an abstract class over an interface would be when you want the classes to inherit an implementation, not just a declaration. This is especially useful when you need to write the same code for multiple classes in your project. With an abstract class, changing implementation becomes much easier and faster. An interface is preferable when you simply want a class to be contracted to perform a set of actions. For example, if you needed a group of classes to react to a button click, but each reaction was different, an interface would be preferable since the set of classes would be contracted to have an implementation for it. An interface is also used when an abstract class is already extended, since a class may only extend one abstract class.

Define what generics are and write what needs to be passed as parameters for the following statement:


public <T, V, S> void doSomething(...) {}  

Generics are parameterized types. They allow parameters to be generalized and able to accept multiple types instead of just one. Classes, interfaces, and methods can make great use of generics when their usages can be applied to more than one type. In this sense, generics can simplify implementation, as the programmer would no longer need to write and call different methods for each type. Generics can also be restricted, so only certain types are accepted. A simple example of when generics would help is a method called printArray. Normally you’d need to write a function for each type of array (String, int, char, etc), but with generics, you’d only need to write one.

For the method doSomething, the <T, V, S> represents that the parameters of the method are a type (T), a value (V), and a second type (S). If the method declaration was complete, it could like:


public <T, V, S> void doSomething(T type, V value, S second_type) {}

The body of doSomething would then interpret and use the arguments for their respective usages.

What is the difference between coupling and cohesion? Which types of each are considered good software design?

Cohesion represents how related everything in a software element is to each other. There are two types of cohesion: high and low. Let’s use a class as the software element we could evaluate the cohesiveness of. If the methods and variables in the class were tightly related and focused on accomplishing the same task, the class would have high cohesion. On the other hand, if the class accomplished a broad variety of things, and many of the methods and variables stored in the class had little to do with each other, the class would have low cohesion. High cohesion is desirable and considered good software design.

Coupling represents how related a software element is to all other software elements in the project. There are two types of coupling: tight and loose. Let’s again use a class to illustrate how we can evaluate a software element’s coupling. If a class A was strongly related to other classes in the project, meaning a change in class A would affect other classes, class A would be considered to have high coupling. If the opposite were true, meaning class A was weakly connected to the other classes, class A would have low coupling. Low coupling is desirable and considered good programming.

High cohesion and low coupling lead to more concise code that is easier to follow, and they make changing a specific aspect of the code far easier. These traits also make troubleshooting far easier, as you would be able to tell which part of the code was causing the problem much faster.

What is a binary search tree and give an example of when one could be used?

A binary search tree (BST) is a type of data structure used for storing data in an efficient and organized way. A BST consists of a root node and two subtrees, with the root of the subtree on the left being less than the root node and the root of the subtree on the right being greater than the root node. BST’s allow for fast data insertion, removal, and lookup, which is why they are commonly used in search applications. BST’s are also commonly used to sort data.

A BST can be used in any situation where the data is comparable. This could be numbers (numerical), strings (alphabetical), or custom objects that you can compare. Anything that fits this criteria can be used as an example of when a BST could be used.

For example, if you had a Person object and wanted to sort of list of Persons by age, you could use a BST. You would construct a BST with the Persons using age as the comparable factor. Then you would simply navigate through the list from left to right to get a sorted list of Persons by age.

Note: Many interviews may ask you to construct a BST, so if you have some extra time, I would suggest you learn how to create one. Resources can be found online for how to do so.

What is the difference between a HashMap and a HashTable? When would you use one over the other?

HashMaps and HashTables are both data structures that store key-value pairs. A key-value pair consists of an object or value called the key and its associated value or data. Examples of key-value pairs are (1, “Bob”), (“January”, “Winter”) with 1 and January being keys and Bob and Winter being the values. When inserting a key-value pair into a HashMap or Hashtable, the key is put through a hash function which outputs an index that corresponds to the key, and the value is stored there (the hash function plays a large role in the efficiency of the HashMap or HashTable, as a good hash function results in fewer collisions when inserting a key-value pair. Collisions may either slow down the data retrieval or force the HashMap or HashTable to resize and rehash).

The main differences between a HashMap and a HashTable are:

HashMap is generally preferred over HashTable when a program does not include multithreading. Since HashMap is non-synchronized, it is not safe to be used with multiple threads.

How do you make an immutable object? Why would an immutable object be useful?

Immutable objects are objects that cannot be changed after they are constructed. There are several key requirements an object must satisfy to be considered immutable:

FYI, a defensive copy is a deep copy of the object. For example, using requirement 6, if I wrote a function that returned an ArrayList myList, I would first create a deep copy of myList, and then return the deep copy.

Immutable objects are very useful when multithreading. Since they cannot be changed, they are not prone to thread interference and do not require synchronization. In addition to multithreading, immutable objects are great map and set keys. Keys must be constant and immutable objects cannot be changed.