Java interview questions (that you need to master)

Developed by James Gosling in 1982, Java is based on object-oriented programming to develop large-scale applications.  With a user community of more than ten million software developers worldwide and over 15 billion devices using Java, is fair to say that it is used everywhere. From applications for Big Data to household devices like mobiles and DTH boxes, Java is the most in-demand certification in programming.

There is a clear reason for that. In terms of application development, Java stands out as one of the simplest, yet powerful high-level languages in terms of standards and useful tools. Being one of the first languages to provide threading support to tackle concurrency-based problems, Java has at the same time an easy-to-use syntax and built-in features. It also excels in terms of stability to resulting applications, so it is not a surprise that this language has an ever-growing number of adepts in the software community.

So, if you are looking forward to getting a job related to this language, we have selected the most commonly asked Java interview questions and the respective answers, at both basic and advanced levels. 

We also had included several Java Code Challenges that will help you to be more prepared for your interview ahead. So when you had mastered our selection, you will be ready to excel in your Java interview.

Multiple job opportunities.
One code challenge.

Get rid of repetitive hiring processes for all the positions you apply to, and access many job offers by taking a single real-world assessment.

Basic Java questions

Is Java a platform-independent language?

Yes, it is. Java was developed to be independent of hardware or software requirements: when the compiler compiles the Java code, it is converted to a platform-independent byte code that can be run on multiple systems, with the only requirement that the machine has a runtime environment (JRE) installed in it.

Since de JRE environment is spread worldwide, it is fair to say that a Java code can run no matter the platform.

Is Java a pure object-oriented language?

Not quite, since as a programming language it supports primitive data types that do not directly belong to the Integer classes (byte, boolean, char, short, int, float, long, and double). 

However, everything in Java is under the classes and we can access that by creating the objects. Therefore, it is best to say that Java is based on object-oriented programming. 

Which are the main differences between Java and C++?

While C++ is a compiled language, Java is both a compiled and interpreted language. While programs in C++ must be compiled for each platform in which they will run, Java applications are machine-independent.

Another difference is that C++ allows users to use pointers, whereas Java does not. Also, C++ supports the concept of multiple inheritances. Java doesn't, to avoid the complexity of name ambiguity resulting in the diamond problem.

Why Java does not use pointers?

Although proven useful in C++, pointers are quite complicated and unsafe to use by beginner programmers and may lead to potential errors. Another drawback of pointers is that they can be used to access memory directly, being a security hazard. Moreover, the usage of pointers can make memory garbage collection slow and erroneous.

Then, Java focuses on code simplicity and uses references, which cannot be manipulated. 

What are JDK, JRE and JVM?

JDK stands for Java Development Kit, JRE for Java Runtime Environment and JVM is Java Virtual Machine.

With JDK we compile code and package Java programs. JRE is a runtime environment in which Java bytecode can be executed on any platform, while JVM is an abstract machine that provides a run-time environment in which Java bytecode can be executed.

What is the JIT compiler?

JIT is the Just-In-Time compiler, used for improving performance during run time. It compiles parts of byte code with similar functionality simultaneously, to reduce the compilation time for the code to run. The JIT acts as a translator of source code to machine-executable code for JVM, increasing the performance and speed of the run.

What are instance and local variables?

Instance variables are those that are accessible by all the methods in a given class, declared outside the methods but inside the class. They describe the properties of an object and remain bound to it, so all the objects of the class will have their copy of the variables. If any modification is done, only that instance will be changed while all other class instances will remain the same.

On the other hand, local variables are those presented within a block, function, or constructor; and they can only be accessed inside them. Therefore, variable use is restricted to the block scope: other class methods will not have any knowledge regarding those local variables.

Explain what are constructors in Java

In Java there are no default values assigned to the variables: we need to initialize them to avoid the Variable might not be initialized compilation error. Depending on the data type, we use constructors to do that. 

A constructor refers to a block of code used to initialize an object. It has the same name as the class, no return type, and is automatically called when the object is created. Regarding to their types, there are two different constructors:

Default constructor: it does not take any inputs. It is a no-argument constructor, created by default if no other constructor is defined by the user. The default constructor initializes the instance variables with the default values and it is used for object creation. 

Parameterized constructor: in Java, it is a constructor capable of initializing the instance variables with values provided by the user. Any constructor that takes arguments is, therefore, a parameterized constructor.

What is a super keyword and when can we use it?

Super keywords are reference variables, which refer to an immediate parent class object. When we create a subclass instance, an instance of the parent class is also created and can be referenced by the super reference variable.

In Java, a super keyword is used to refer to an immediate parent class instance variable, using super. That keyword can be used to call the method of an immediate parent class, while    Super() calls the constructor of the immediate parent class.

Advanced Java interview questions 

Explain why the inheritance is sometimes less advantageous than composition in Java

Even when inheritance is a popular OOPs concept, it lags behind composition since multiple inheritance is not possible in Java. In cases where multiple functionalities are required, the pattern of composition is preferred since it provides high flexibility and maintains encapsulation.

Also, unit testing is possible with composition when we want to test a class composing a different class. This technique is not possible with inheritance, because the derived class cannot be tested without the help of the superclass. 

Therefore, the loosely coupled nature of the composition is sometimes preferable to the coupled nature of inheritance.

Why make strings immutable in Java?

A String is made immutable if used as:

String Pool: is a storage area in Java heap to store the String literals, to decrease the temporary String object with the help of sharing. 

Multithreading: No external synchronization is required if the String objects are immutable, so cleaner code can be written for sharing the String objects across different threads. 

Collections: In Hashtables and HashMaps, keys are immutable String objects to avoid they can get modified during the period when it resides in the HashMaps. 

State the difference between the ‘>>’ and ‘>>>’ operators 

Both are the bitwise right shift operators, but the first is the Bitwise Right Shift Operator ( ‘>>’), which shifts each bit to its right position maintaining the signed bit. The other, the Bitwise Right Shift Operator with trailing zero ( ‘>>>’) also shifts each bit to its right, but making the signed most significant bit to 0.

What is the difference between composition and aggregation? 

Both help to build a relationship between classes and objects, but in a different way. For instance, let's said that the container object “house” as a class with some “rooms” in it (objects). If the container object is destroyed, the contained objects will be gone too.  Therefore, there is a strong association between objects, and this is called composition.

Now, let’s suppose that we have a class “room” and there are several “furniture” objects on it. If the “room” class is destroyed, the “furniture” object will become free to be moved and bind with other “room” objects. In this case, the container objects (rooms) only hold the references of contained objects (furniture), resulting in a weak association between the objects that is called aggregation.

It is possible to exceed the memory limit in a program, even if a garbage collector is used?

Yes, the program can still go out of memory. Garbage collection helps to recognize and eliminate objects which are not required in the program further to free up resources. But if an object is unreachable during the run, the execution of garbage collection takes place with respect to that object. 

Then, if the amount of memory required for creating a new object is not enough and the garbage collector cannot release the one used by those unreachable objects, the memory limit will be exceeded.

If objects are created in a way that they remain in the scope, consuming memory, the heap memory will become exhausted. Therefore, even when the garbage collector makes its best to reclaim used memory, as developers we should make sure to dereference the object after its functions are completed. 

Explain the Java thread lifecycle

In Java, a thread can be:

New: the instance of the thread is created but the start() method has not been invoked. 

Runnable: the start() method is invoked but the run() method has not been called yet by JVM. 

Running: the run() method has been invoked and the thread starts its execution.

Non-Runnable (Blocked/Waiting): the thread is alive but not able to run. When a thread wants to enter synchronized code but another thread is already operating in that block on the same object, the thread will be blocked. If a thread is waiting for the signal to execute from another thread, it will be in a waiting state.

Terminated: when the run() method execution is completed, the thread is considered dead.

Why is synchronization necessary in Java? 

With synchronization, we can perform concurrent execution of different processes. But also can be the case that a particular resource is shared between many threads at the same time. For instance, if we need to find out the number of requests made to a URL and two requests is made at the same time, results can be erratic. Synchronization helps to resolve this issue, making the shared resource available to a single thread each time. 

State the differences between interfaces and abstract classes

They can be differentiated by their respective properties:    

Availability of methods: While only abstract methods are available in interfaces, non-abstract methods can be present among abstract methods in abstract classes.

Variable types: We can only declare static and final variables in interfaces, whereas abstract classes can contain non-static and non-final variables.

Inheritance: Multiple inheritances are promoted in interfaces, while abstract classes do not facilitate multiple inheritances.

Data member accessibility: the class data members of interfaces are mostly of the public- type, whereas the class members for an abstract class allow the protected and private type instead.

Implementation: it is easy to implement an interface using an abstract class, but not otherwise: we cannot create an abstract class using an interface.

What is a marker interface in Java?

Marker interfaces (AKA tagging interfaces) are those that have no methods or constants defined in them. Their function is to help the compiler and JVM to get run time-related information regarding the objects.

Java Code Challenges 

So, with these challenges, we have reached the end of this article on Java Interview Questions. We hope that you feel now more confident and remember: make sure you study and practice as much as possible. Good luck with that interview ahead!

Multi-apply: How to apply to many job opportunities with one single Challenge

We have managed to get most of the companies we collaborate with to adopt our Rviewer challenges in their validation process as an official test.

And here's the bomb: This allows us to offer you, at last, Multi-Apply: with a single technical challenge you will be able to access more than one job offer. Yes, you heard it right: MANY job opportunities by taking a SINGLE code challenge.

Master coding interviews for growing tech companies

Discover here the ultimate guide to coding interview processes. Find out how they work and how you can optimize yourself as a developer to attract the attention of tech companies and get better results in their coding interviews.

Related articles

Stay tuned: receive the latest product updates

Subscribe to our newsletter to keep up with the latest trends!