Java Interview Questions for a Technical Interview

A technical interview is an integral part of the hiring process for a software engineer. And while some interview questions will be unique for your specific company, there is a set of common questions that are always asked with the aim to test one’s technical knowledge. In this article, we’ve collected the most common questions on Java that one might expect during the interview. We hope these Java interview questions will help you prepare for the upcoming interview or they will simply refresh your memory and knowledge of Java.

Java Interview Questions for a Technical Interview

Why is String immutable?

String is not a primitive type in Java. It is defined as a public final class. So this keyword makes String immutable. Why is it necessary? String helps to keep all strings in the string pool in the Java memory and to use it as a unique key. This is very important when we use strings as keys, or when we store secure passwords in a database.

The immutability of the String helps avoid situations when a hacker tries to forge your password or other sensitive information. So instead of changing, a new line is created with a new link and a hashcode. Also, String is thread-safe due to its immutability.

What is a collection? 

The collection is a Java framework that helps to perform a lot of operations with data such as sorting, searching, manipulation, insertion, etc.

Interface Collection extends from interfaces Iterable. And the following interfaces are extended from it: Set, Queue, List. 

  • ArrayList, LinkedList implements the interface List.
  • ArrayList is essentially an array of data where each element has its own index.
  • LinkedList is a data chain. Each element of the list stores a reference to the previous and next elements.
  • Set is the unsorted data that does not allow you to save duplicates. Also, it can keep only one null value.
  • HashSet is the collection that implements interface Set and uses a hash table for storage.
  • LinkedHashSet preserves insertion order.

How does HashMap work internally?

When talking about the most common Java interview questions, it is worth mentioning the Map interface and its implementation known as HashMap which is a collection of entry points (key and value). Data is kept in 16 baskets by default. When we want to put an entry into a map, we have to calculate the hashcode for the key, and then apply hash() function for it. As a result, we get a number of busts for our value.

What is Spring?

Spring is an open-source Java framework. It is a dependency injection container. Spring helps you to create a Java application in a fast and comfortable way. This container manages your classes and class dependencies too. In addition, Spring helps to create and inject all dependencies and configurations and then put them into context, where they are kept while the app is running (or not – it depends on the bean scope).

What is Spring Boot? 

Spring boot is one of the frameworks in the Spring ecosystem. It helps to create apps quickly with special spring-boot-starters dependencies. All you need is to add it to your pom.xml or and start to develop. You don;t need to think about any configurations like configs for Hibernate (if you use spring-data-jpa) or Tomcat. It has configurations “from the box”. But if you want, you can configure that project as you wish.

How to work with Authentication in Spring Security?

When we speak about Spring Security we normally use the Authentication object. Before authentication, the field Princical keeps only the username, the field Credential keeps the password and the field “isAuthenticated” = false. After authentication, we return the Authentication object again. But in this case, Princical keeps UseDetails object, Credential = null and  “isAuthenticated” = true. 

How to secure Restful web services? 

When we want to configure access for any endpoint, we can do it with several methods:

1. In SecurityConfig – using antMathers pattern;


2. In the service or controller layer – use annotations like “@PreAuthorithed” or “@Secured”. 

public String getUsername() {
    // do smth

public String getUsername() {
    // do smth

We can configure access depending on any Roles or Permissions.

What is JWT in Spring security?

JWT is a JSON object which is one of the most secure ways of transmitting information between two members. It includes a header, a payload and a signature. How does it work? 

A user sends a login and a password to the authorization server, which authorizes the user and returns JWT. The user uses it when making API calls to the App server. The server verifies JWT and invokes a call. It is important to remember though that JWT does not encrypt the payload information. It only helps to verify if the information is really sent from authorized users. 

What is Singleton?

In Spring, we are dealing with several types of bean scopes. By default, the scope of any bean is a singleton. This means that the bean is created immediately when the application is launched at the stage of creating the context. It is also fully configured and placed in the Spring container. A Singleton means that the given object has one and only one implementation. And every call to an instance of the class will be made to the same instance.

What are annotations in Java?

Annotation is a marker, which we use in classes, methods, or fields. Sometimes it’s enough (for example @Override annotation), but sometimes it also includes additional logic. In that case we must create (or use) a handler of annotations for it. For creating our custom annotations we must declare it by using the @interfase keyword. Then we add metainfo to specify the scope and the target. 

public @interface MyCustomAnnotation {

And finally, we must develop a handler for annotation by using Java Reflection API.

private void checkIfHasAnnotation(Object object) {
   if (Objects.isNull(object)) {
       //do smth

   Class<?> clazz = object.getClass();
   if (!clazz.isAnnotationPresent(MyCustomAnnotation.class)) {
       //do smth

Now we can use our annotation @MyCustomAnnotation in the code.

Class vs Object 

Class and object are the main things to learn in Java. Java is an OOP language. Thus, we can represent the entire code as the interaction of various objects with each other. A class is a template for implementing an object. Many objects can be created based on one class. We can describe it this way: the class is the recipe for cooking the dish, and the object is the dish itself.

What is the version of Java and what are the major changes in versions?

Among the main Java interview questions this one might be the easiest but some developers tend to overlook it. So, what do you need to know about Java versions?

The first version of Java was created in 1996. And in 2023 we now have versions from JDB Beta, JDK 1.0 to JDK 18. But we can use in production only the LTS (long-term support) versions. The following LTS versions are most common at the moment: JDK 8, JDK 11, and JDK 17. Major changes in versions:

  • JDK 8 – functional interfaces, lambda, stream API, date & time API
  • JDK 11 – HttpClient, removing Java EE modules
  • JDK 17-  Vector API, Memory API, deprecated Security Manager

What is an interface in Java?

An interface is a reference data type and it contains methods with and without implementation. An interface may be implemented in a class and the logic of all methods is implemented there, or existing implementations can be used. Java allows you to implement several interfaces, as opposed to class extending. An interface can also extend other interfaces. It allows you to work with abstractions and get more flexible, dynamic and less coupled code

What is lambda expression in Java? 

A lambda expression is a block of code that takes parameters and returns a value. Unlike a method, a lambda expression does not need to be given a name and can be implemented directly in the code. The syntax of a lambda expression is as follows:

(param1, param2) -> (doSmth(param1, param2))

For complex operations, you can use the block of code after the arrow:

(param1, param2) -> {
   return doSmth3(param1, param2);

Lambda expressions are widely used in the Stream API.

What is the difference between final,finalize() and finally?

final is a java modifier meaning that the class/variable is immutable (constant). A class marked as final cannot have a child class. A method marked as final cannot be overridden. 

finalize() is a method of the Object class that is called before the garbage collector removes the object from the memory. Most often, overriding this method is required when it is necessary to close some resources before deleting an object. In Java 18 the finalize() is deprecated

finally{} is a block that is used in conjunction with try/catch blocks. It contains code that will be executed on any outcome of the try-block. As a rule, the code is placed in the finally block, which closes the previously opened resources. Try-with-resources can be used instead of the finally block.

You might also find these articles interesting:

What is reflection in Java? 

Reflection is an API that allows you to get information about class variables, its constructors and methods, including private ones. Reflection is often used when writing frameworks and testing. Using reflection during development is considered bad manners and indicates that the project’s architecture needs to be redesigned.

What is static in Java?

The static modifier means that the variable/method with which it was applied is shared by the entire class and can be used without creating an instance of the class. If we have multiple instances of the same class with a static variable/method, then they will all refer to the same variable/method. In addition to static variables, static{} blocks are used. Such blocks are initialized before the class is instantiated.

What is an abstract class in Java? 

An abstract class is a class that has an abstract keyword. This class can also have variable methods (defined or not), but it is not possible to create an instance of this class. An abstract class was created in order to implement functionality in its child classes. An abstract class has a lot in common with an interface in Java. It also implements one of the basic principles of OOP aka polymorphism.

What is Stream API in Java?

This API was introduced in Java 8. Its purpose is to make it easier to work with datasets such as collections. Also, lambda expressions can be used in streams. 
There are two types of operations in streams: intermediate and terminal. 

List<String> list = List.of("anna", "alex", "fred", "alice", "alla", "alfred", "sam"); //create stream
       .filter(s -> s.startsWith("a")) //intermediate operation with lambda-expression
       .limit(3) //intermediate operation
       .skip(1)//intermediate operation
       .forEach(System.out::println); //terminate operation
What is Stream API in Java?

Result : “alex”, “alice” 

There can be any number of intermediate operations, but there is only one final operation. The principle of the flow is as follows: operations on the data begin only when a terminal operator is reached. This leads to the downside of threading – it takes longer than a normal amount of time for a loop.

What are exceptions in Java?

Exceptions are errors or unexpected situations that occur at the stage of compiling or running a program. In Java, all exceptions extend the Throwable class and are divided into two large groups: exceptions and errors. Exceptions, in turn, are checked and not checked (Runtime Exception). Unchecked exceptions occur during code execution and cannot be tracked down during the compile time. 

Examples of such errors are division by zero (ArithmeticException) or incorrect cast (ClassCastException). Errors, like Runtime Exceptions, are unchecked. Errors include situations after which further operation of the application is impossible: for example VirtualMachineError. Checked exceptions can be caught at compile time. They must be handled in one of the following ways: 

1. Wrapped in a try-catch block; 

try {
    //your code
} catch (Exception e) {
    //your code

2. Throw the exception above with ‘throws’.

public String yourMethod(String str) throws Exception { 
   //your code

How to create custom exception?

Creating your own exception is necessary when developing the business logic of an application, when standard exceptions do not give complete information about the reason. To create your own exception, you need to create a class and extend from the Exception or RuntimeException class. Accordingly, your exception will be checked or unchecked. 

public class MyCustomException extends Exception { 
    //your code

Then you need to add a class constructor with a String parameter (error message) and call the superclass constructor inside. 

public class MyCustomException extends Exception { 
    public MyCustomException(String errorMessage) {

That’s all! You can use your exception and handle it where necessary.

How do access modifiers in Java?

Java has 4 access modifiers: public, private, protected, and default. The strictest modifier is private. Variables and methods that have this modifier are visible only at the level of the class to which they belong. Next comes the protected modifier. In this case, the data is available within the class itself and child classes. If a field or a method does not have an access modifier, then the default modifier is applied to it. This modifier gives access at the package level. The modifier with the widest access is public. Data with this modifier is available both inside and outside the package.

Summing up

We hope these Java interview questions were helpful to you and refreshed your memory on the main features of Java. Comment on th questions that you got right or list those questions that we did not include – we’d love to hear from you!

Want to stay updated on the latest tech news?

Sign up for our monthly blog newsletter in the form below.

Softteco Logo Footer