50+ Java Interview Questions for Programmers

Hello, guys! Recently, I have been sharing a lot of Java Interview questions and discussion individually, and many of my readers requested to bring them together so that they can have them in the same page and prepare better and this post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection FrameworkJava Multithreading and ConcurrencyJava IOJDBCJVM InternalsCoding ProblemsObject-Oriented programming, etc.

The questions are also picked up from various interviews and they are, by no means, very difficult, and you might have seen them already in your telephonic or face-to-face round of interview.

The questions are also very good to revise important topics like multithreading and collections as I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for here is the list of some of the frequently asked Java questions from interviews from both beginner and experienced Java developer of 2 to 5 years experience:

Java Interview Questions and Answers

1)  How Java achieves platform independence? (answer)
hint: bytecode and Java Virtual Machine

2)  What is ClassLoader in Java? (answer)
hint: part of JVM that loads bytecodes for classes. You can write your own.

3)  Write a Java program to check if a number is Even or Odd? (answer)
hint: you can use bitwise operator, e.g. bitwise AND &, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

4)  Difference between ArrayList and HashSet in Java? (answer)
hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc.

5)  What is double checked locking in Singleton? (answer)
hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6)  How do you create thread-safe Singleton in Java? (answer)
hint: many ways, e.g. using Enum or by using double-checked locking pattern or using a nested static class.

7)  When to use volatile variable in Java? (answer)
hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8)  When to use a transient variable in Java? (answer)
hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9)  Difference between the transient and volatile variable in Java? (answer)
hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? (answer)
hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? (answer)
hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between Hashtable and HashMap in Java? (answer)

hint: several but most important is Hashtable, which is synchronized, while HashMap is not. It’s also legacy and slow as compared to HashMap.

13) Difference between Listand Set in Java? (answer)
hint: List is ordered and allows duplicate. Set is unordered and doesn’t allow duplicate elements.

14) Difference between ArrayList and Vector in Java (answer)
hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It’s also legacy class like Hashtable.

15) Difference between Hashtable and ConcurrentHashMap in Java? (answer)
hint: more scalable

16) How does ConcurrentHashMap achieve scalability? (answer)
hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an Object to be used as Key in HashMap? (answer)
hint: equals and hashcode

18) Difference between wait and sleep in Java? (answer)
hint: The wait() method releases the lock or monitor, while sleep doesn’t.

19) Difference between notify and notifyAll in Java? (answer)
hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with equals() in Java? (answer)
hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList.

21) What is the load factor of HashMap means? (answer)
hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it’s 75 percent full.

22) Difference between ArrayList and LinkedList in Java? (answer)
hint: same as an array and linked list, one allows random search while other doesn’t. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections Richard Warburton course on Pluralsight to learn more about essential Collection data structure in Java.

23) Difference between CountDownLatch and CyclicBarrier in Java? (answer)
hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch   after the count reaches to zero.

24) When do you use Runnable vs Thread in Java? (answer)
hint: always

25) What is the meaning of Enum being type-safe in Java? (answer)
hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? (answer)
hint: using valueOf() method

27) Difference between PATH and Classpath in Java? (answer)
hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATHClasspath, and other Java environment variable.

28) Difference between method overloading and overriding in Java? (answer)
hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? (answer)
hint: just make its constructor private

30) How do you restrict your class from being used by your client? (answer)
hint:  make the constructor private or throw an exception from the constructor

31) Difference between StringBuilder and StringBuffer in Java? (answer)
hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? (answer)
hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? (answer)
hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? (answer)
hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? (answer)
hint: from Java 8, the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? (answer)
hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? (answer)
hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

38) Difference between fail-safe and fail-fast iterators in Java? (answer)
hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? (answer)
hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is IdentityHashMap in Java? (answer)
hint: A Map, which uses  the == equality operator to check equality instead of the equals() method.

41) What is String pool in Java? (answer)
hint: A pool of String literals. Remember it’s moved to heap from perm gen space in JDK 7.

42) Can a Serializable class contain a non-serializable field in Java? (answer)

hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? (answer)
hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between Comparator and Comparable in Java? (answer)
hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to learn more about sorting in Java.

45) Difference between java.util.Date and java.sql.Date in Java? (answer)
hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in Object class in Java? (answer)
hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? (answer)
hint: It doesn’t support because of bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? (answer)
hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? (answer)
hint: I am tired of typing please check the answer

50) Difference between race condition and deadlock in Java? (answer)
hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding.

Additional Resources

Lifecycle of a Request-Response Process for a Spring REST API

Developing a REST API or microservice using the Spring Boot framework accelerates the development process, and allows API developers to only focus on writing the core business logic and not worry about all the underlying configurations and setup. This article describes the steps involved in the lifecycle of a request process and how the request is mapped to the appropriate controller method and how a response is returned to the client.

In order to create a REST API to serve a client with a list of users, the tasks involved are

  • Create a class with the @RestController annotation. Due to the annotation, this class will be auto-detected through classpath scanning and the methods annotated with @RequestMapping annotation will be exposed as HTTP endpoints. When an incoming request matches the requirements specified by the @RequestMapping annotation, the method will execute to serve the request.

For our example of a users API, the controller class will look like this:

@RestController
@RequestMapping("/users")
public class UserController {
                @Autowired
                UserService userService

                @RequestMapping(method = RequestMethod.GET)
                public List<UserDTO> findAllUsers() {
                                return userService.findAllUsers();
                }
}
  • Create a class for business logic.
  • Create a class to fetch data from the user table.

From a developer’s perspective, the flow to fetch the list of users from the database can be viewed as below:Image titleHowever, with Spring doing a lot of work for us behind the scenes, the lifecycle of the entire process for making an HTTP request to a resource to serving the response back to the client in either XML/JSON format involves many more steps.

This article describes the entire request to response lifecycle with steps which are managed by Spring.

When a user makes a request for a resource, for example:

Request: http://localhost:8080/users 

Accept: application/json 

This incoming request is handled by the DispatcherServlet, which is auto-configured by Spring Boot. While creating a project through the Spring Boot framework, and when we mention the Spring Boot Starter Web as a dependency in pom.xml, Spring Boot’s auto-configuration feature configures dispatcherServlet, a default error page, and other dependent jar files.

When a Spring boot application is run, the log will have a message like this:

[ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: ‘dispatcherServlet’ to [/]

DispatcherServlet is the front controller and all incoming request goes through this single servlet.

The process from a request to response is shown in the below flow chart:

Image title

The blocks in the green are the ones which are implemented by developers.

In our request for /users resources, the activities below are performed in each step:

  1. In Step 1, the dispatcher servlet will intercept the request for the resource /users.
  2. In Step 2, the servlet determines the handler for the request (a good link on this topic).
  3. In Step 3, Spring checks which controller method matches the incoming lookup path of the “/users” request. Spring maintains a list of all mapping registries fetched from the @RequestMapping of the controller class and iterates the list to look for the matching method in the controller class implemented by the developer.
  4. In Step 4, after determining the right method it executes the controller method.
  5. Step 5 returns an ArrayList of users.
  6. The response type accepted by the client can be either JSON or XML. Therefore, Step 6 does the job of marshaling the Java object to the response type requested by the client. Spring takes the ArrayList of users and uses the message converter method to marshal it to the type requested by the client. If the converted message is not available, then the client will get a 406 error. In the case of users, as the requested type is JSON, thus a JSON object for users is returned as a response.

Conclusion

Understanding the lifecycle of the request and response process and other classes involved helps one to understand the issues better and troubleshoot it more easily. To check the process lifecycle, open the Eclipse Open Type DispatcherServlet class and add a breakpoint at the doDispatch method.

@RestController vs @Controller : Spring Framework

Spring MVC Framework and REST

Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Image title

Figure 1: Spring MVC traditional workflow

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

3.x-diagram

Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
  3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model;
import javax.xml.bind.annotation.XmlRootElement;
 @XmlRootElement(name = “Employee”)
 public class Employee {
     String name
      String email;
    public String getName() {
       return name;
    }
    public void setName(String name) {
       this.name = name;
    }
     public String getEmail() {
                 return email;
     }
     public void setEmail(String email) {
       this.email = email;
     }
     public Employee() {
     }
 }

Then, create the following @Controller class:

 package com.example.spring.rest;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.spring.model.Employee;
@Controller
@RequestMapping("employees")
public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
     return employee;
    }
    @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
        return employee;
     }
 }
 Notice the @ResponseBody added to each of the @RequestMapping methods in the return value. After that, it’s a two-step process:
  1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:output_json-cropXML — Use the
    URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:output_xml

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.
4.x-diagram

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

 package com.example.spring.rest;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
 import com.example.spring.model.Employee;
@RestController
 @RequestMapping(“employees”)
 public class EmployeeController {
     Employee employee = new Employee();
     @RequestMapping(value = “/{name}”, method = RequestMethod.GET, produces = “application/json”)
     public Employee getEmployeeInJSON(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
        return employee;
    }
     @RequestMapping(value = “/{name}.xml”, method = RequestMethod.GET, produces = “application/xml”)
     public Employee getEmployeeInXML(@PathVariable String name) {
        employee.setName(name);
        employee.setEmail(“employee1@genuitec.com”);
     return employee;
     }
 }

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.

Conclusion

As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!

@RestController vs. @Controller : Spring Framework

Spring MVC Framework and REST

Spring’s annotation-based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Image title

Figure 1: Spring MVC traditional workflow

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions, and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view.

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

3.x-diagram

Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.• If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.• In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically.
  3. Create the following Java class named Employee. This class is our POJO.
package com.example.spring.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Employee")
public class Employee {
 String name; 
 String email;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getEmail() {
 return email;
 }
 public void setEmail(String email) {
 this.email = email;
 }
 public Employee() {
 } 
}
 Then, create the following @Controller class:
package com.example.spring.rest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.spring.model.Employee;
@Controller
@RequestMapping("employees")
public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public @ResponseBody Employee getEmployeeInXML(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 }
}
 Notice the @ResponseBody added to each of the @RequestMapping methods in the return value. After that, it’s a two-step process:
  1. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    • <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    • <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  2. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:output_json-crop

    XML — Use the
    URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:output_xml

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.
4.x-diagram

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

package com.example.spring.rest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.spring.model.Employee;
@RestController
@RequestMapping("employees")
public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public Employee getEmployeeInJSON(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee;
 }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public Employee getEmployeeInXML(@PathVariable String name) {
 employee.setName(name);
 employee.setEmail("employee1@genuitec.com");
 return employee; 
 } 
}

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.

Conclusion

As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information!

Difference between Setter vs Constructor Injection in Spring

Spring Setter vs Constructor Injection

Spring supports two types of dependency Injection, using setter method e.g. setXXX() where XXX is a dependency or via a constructor argument. The first way of dependency injection is known as setter injection while later is known as constructor injection. Both approaches of Injecting dependency on Spring bean has there pros and cons, which we will see in this Spring framework article. The difference between Setter Injection and Constructor Injection in Spring is also a popular Spring framework interview question.Some time interviewer also asks as When do you use Setter Injection over Constructor injection in Spring or simply benefits of using setter vs constructor injection in Spring framework. Points discussed in this article not only help you to understand Setter vs Constructor Injection but also Spring’s dependency Injection process.

By the way, if you are new in Spring framework and learning it, you may want to take a look at my list of 5 good books to learn Spring framework. That will certainly help in  your learning process. Since Spring is now a must have skill for Java programmers, it worth putting time and effort to learn this powerful framework

Difference between Setter and Constructor Injection in Spring framework

As I said earlier Spring supports both setter and constructor Injection which are two standard way of injecting dependency on beans managed by IOC constructor. Spring framework doesn’t support Interface Injection on which dependency is injected by implementing a particular interface. In this section we will see a couple of difference between setter and constructor Injection, which will help you decide when to use setter Injection over constructor Injection in Spring and vice-versa.

1) The fundamental difference between setter and constructor injection, as their name implies is How dependency is injected.  Setter injection in Spring uses setter methods like setDependency() to inject dependency on any bean managed by Spring’s IOC container. On the other hand constructor injection uses constructor to inject dependency on any Spring-managed bean.
2) Because of using setter method, setter Injection in more readable than constructor injection in Spring configuration file usually applicationContext.xml . Since setter method has name e.g. setReporotService() by reading Spring XML config file you know which dependency you are setting. While in constructor injection, since it uses an index to inject the dependency, it’s not as readable as setter injection and you need to refer either Java documentation or code to find which index corresponds to which property.
3) Another difference between setter vs constructor injection in Spring and one of the drawback of  setter injection is that it does not ensures dependency Injection. You can not guarantee that certain dependency is injected or not, which means you may have an object with incomplete dependency. On other hand constructor Injection does not allow you to construct object, until your dependencies are ready.
4) One more drawback of setter Injection is Security. By using setter injection, you can override certain dependency which is not possible which is not possible with constructor injection because every time you call the constructor, a new object is gets created.

5) One of our reader Murali Mohan Reddy pointed out one more difference between Setter and Constructor injection in Spring, where later can help if there is a circular dependency between two object A and B.
If Object A and B are dependent each other i.e A is depends ob B and vice-versa. Spring throws ObjectCurrentlyInCreationException while creating objects of A and B bcz A object cannot be created until B is created and vice-versa. So spring can resolve circular dependencies through setter-injection. Objects constructed before setter methods invoked.
See comment section for more inputs from other readers.

When to use Setter Injection over Constructor Injection in Spring

Setter Injection has upper hand over Constructor Injection in terms of readability. Since for configuring Spring we use XML files, readability is much bigger concern. Also drawback of setter Injection around ensuring mandatory dependency injected or not can be handled by configuring Spring to check dependency using “dependency-check” attribute of  tag or tag. Another worth noting point to remember while comparing Setter Injection vs Constructor Injection is that, once number of dependency crossed a threshold e.g. 5 or 6 its handy manageable to passing dependency via constructor. Setter Injection is preferred choice when number of dependency to be injected is lot more than normal, if some of those arguments is optional than using Builder design pattern is also a good option.
In Summary, both Setter Injection and Constructor Injection has there own advantage and disadvantage. The good thing about Spring is that it doesn’t restrict you to use either Setter Injection or Constructor Injection and you are free to use both of them in one Spring configuration file. Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.

 

Spring Security Example Tutorial – How to limit number of User Session in Java

Spring security can limit number of session a user can have. If you are developing web application specially secure web application in Java J2EE then you must have come up with requirement similar to online banking portals have e.g. only one session per user at a time or no concurrent session per user. You can also implement this functionality without using spring security but with Spring security its just piece of cake with coffee :). Spring Security provides lots of Out of Box functionality a secure enterprise or web application needed like authentication, authorization, session management, password encoding, secure access, session timeout etc. In our spring security example we have seen how to do LDAP Authentication in Active directory using spring security and in this spring security example we will see how to limit number of session user can have in Java web application or restricting concurrent user session.

Spring Security Example: Limit Number of User Session

As I said it’s simple and easy when you use spring security framework or library. In fact is all declarative and no code is require to enable concurrent session disable functionality. You will need to include following xml snippet in your Spring Security Configuration file mostly named as applicaContext-security.xml. Here is sample spring security Example of limiting user session in Java web application:

<session-management invalid-session-url="/logout.html">
    <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>

As you see you can specify how many concurrent session per user is allowed, most secure system like online banking portals allow just one authenticate session per user. You can even specify a URL where user will be taken if they submit an invalid session identifier can be used to detect session timeout. Session-management element is used to capture session related stuff. Max-session specify how many concurrent authenticated session is allowed and if error-if-maximum-exceeded set to true it will flag error if user tries to login into another session.

Dependency

This code has dependency on spring-security framework. You need to download spring security jar like spring-security-web-3.1.0.jar and add into application classpath.

This simple example of spring security shows power of spring security, a small piece of xml snippet can add very useful and handy security feature in your Java web application. I recommend using spring security for your new or existing Java web application created using Servlet JSP.

That’s all on how to limit number of user session using spring security in Java web application. Let me know if you face any issue while implementing this security feature in your project.

 

An Intro to the Spring DispatcherServlet!

1. Introduction

Simply put, in the Front Controller design pattern, a single controller is responsible for directing incomingHttpRequests to all of an application’s other controllers and handlers.

Spring’s DispatcherServlet implements this pattern and is, therefore, responsible for correctly coordinating the HttpRequests to their right handlers.

In this article, we will examine the Spring DispatcherServlet’s request processing workflow and how to implement several of the interfaces that participate in this workflow.

2. DispatcherServlet Request Processing

Essentially, a DispatcherServlet handles an incoming HttpRequest, delegates the request, and processes that request according to the configured HandlerAdapter interfaces that have been implemented within the Spring application along with accompanying annotations specifying handlers, controller endpoints, and response objects.

Let’s get more in depth about how a DispatcherServlet processes a component:

  • the WebApplicationContext associated to a DispatcherServlet under the key DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE is searched for and made available to all of the elements of the process
  • The DispatcherServlet finds all implementations of the HandlerAdapter interface configured for your dispatcher using getHandler() – each found and configured implementation handles the request via handle()  through the remainder of the process
  • the LocaleResolver is optionally bound to the request to enable elements in the process to resolve the locale
  • the ThemeResolver is optionally bound to the request to let elements, such as views, determine which theme to use
  • if a MultipartResolver is specified, the request is inspected for MultipartFiles – any found are wrapped in a MultipartHttpServletRequest for further processing
  • HandlerExceptionResolver implementations declared in the WebApplicationContext pick up exceptions that are thrown during processing of the request

You can learn more about all the ways to register and set up a DispatcherServlet here.

3. HandlerAdapter Interfaces

The HandlerAdapter interface facilitates the use of controllers, servlets, HttpRequests, and HTTP paths through several specific interfaces. The HandlerAdapter interface thus plays an essential role through the many stages of the DispatcherServlet request processing workflow.

First, each HandlerAdapter implementation is placed into the HandlerExecutionChain from your dispatcher’s getHandler() method. Then, each of those implementations handle() the HttpServletRequest object as the execution chain proceeds.

In the following sections, we will explore a few of the most important and commonly used HandlerAdapters in greater detail.

3.1. Mappings

To understand mappings, we need to first look at how to annotate controllers since controllers are so essential to the HandlerMapping interface.

The SimpleControllerHandlerAdapter allows for the implementation of a controller explicitly without a @Controller annotation.

The RequestMappingHandlerAdapter supports methods annotated with the @RequestMapping annotation.

We’ll focus on the @Controller annotation here, but a helpful resource with several examples using the SimpleControllerHandlerAdapter is also available.

The @RequestMapping annotation sets the specific endpoint at which a handler will be available within the WebApplicationContext associated with it.

Let’s see an example of a Controller that exposes and handles the ‘/user/example’ endpoint:

1
2
3
4
5
6
7
8
9
10
@Controller
@RequestMapping("/user")
@ResponseBody
public class UserController {
 
    @GetMapping("/example")
    public User fetchUserExample() {
        // ...
    }
}

The paths specified by the @RequestMapping annotation are managed internally via the HandlerMapping interface.

The URLs structure is naturally relative to the DispatcherServlet itself – and determined by the servlet mapping.

Thus, if the DispatcherServlet is mapped to ‘/’, then all mappings are going to be covered by that mapping.

If, however, the servlet mapping is ‘/dispatcher‘ instead, then any @RequestMapping annotations are going to be relative to that root URL.

Remember that ‘/’ is not the same as ‘/*’ for servlet mappings! ‘/’ is the default mapping and exposes all URL’s to the dispatcher’s area of responsibility.

‘/*’  is confusing to a lot of newer Spring developers. It does not specify that all paths with the same URL context are under the dispatcher’s area of responsibility. Instead, it overrides and ignores the other dispatcher mappings. So, ‘/example’ will come up as a 404!

For that reason, ‘/*’ shouldn’t be used except in very limited circumstances (like configuring a filter).

3.2. HTTP Request Handling

The core responsibility of a DispatcherServlet is to dispatch incoming HttpRequests to the correct handlersspecified with the @Controller or @RestController annotations.

As a sidenote, the main difference between @Controller and @RestController is how the response is generated – the @RestController also defines @ResponseBody by default.

A writeup where we go into much greater depth regarding Spring’s controllers can be found here.

3.3. The ViewResolver Interface

A ViewResolver is attached to a DispatcherServlet as a configuration setting on an ApplicationContext object.

A ViewResolver determines both what kind of views are served by the dispatcher and from where they are served.

Here’s an example configuration which we’ll place into our WebMvcConfigurerAdapter for rendering JSP pages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.springdispatcherservlet")
public class AppConfig extends WebMvcConfigurerAdapter {
    @Bean
    public UrlBasedViewResolver viewResolver() {
        UrlBasedViewResolver resolver
          = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }
}

Very straight-forward! There are three main parts to this:

  1. setting the prefix, which sets the default URL path to find the set views within
  2. the default view type which is set via the suffix
  3. setting a view class on the resolver which allows technologies like JSTL or Tiles to be associated with the rendered views

One common question involves how precisely a dispatcher’s ViewResolver and the overall project directory structure are related. Let’s take a look at the basics.

Here’s an example path configuration for an InternalViewResolver using Spring’s XML configuration:

1
<property name="prefix" value="/jsp/"/>

For the sake of our example, we’ll assume that our application is being hosted on:

This is the default address and port for a locally hosted Apache Tomcat server.

Assuming that our application is called dispatcherexample-1.0.0, our JSP views will be accessible from:

The path for these views within an ordinary Spring project with Maven is this:

1
2
3
4
5
6
7
src -|
     main -|
            java
            resources
            webapp -|
                    jsp
                    WEB-INF

The default location for views is within WEB-INF. The path specified for our InternalViewResolver in the snippet above determines the subdirectory of ‘src/main/webapp’ in which your views will be available.

 3.4. The LocaleResolver Interface

The primary way to customize session, request, or cookie information for our dispatcher is through theLocaleResolver interface.

CookieLocaleResolver is an implementation allowing the configuration of stateless application properties using cookies. Let’s add it to AppConfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
public CookieLocaleResolver cookieLocaleResolverExample() {
    CookieLocaleResolver localeResolver
      = new CookieLocaleResolver();
    localeResolver.setDefaultLocale(Locale.ENGLISH);
    localeResolver.setCookieName("locale-cookie-resolver-example");
    localeResolver.setCookieMaxAge(3600);
    return localeResolver;
}
@Bean
public LocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.US);
    localResolver.setDefaultTimeZone(TimeZone.getTimeZone("UTC"));
    return localeResolver;
}

SessionLocaleResolver allows for session-specific configuration in a stateful application.

The setDefaultLocale() method represents a geographical, political, or cultural region, whereas setDefaultTimeZone() determines the relevant TimeZone object for the application Bean in question.

Both methods are available on each of the above implementations of LocaleResolver.

3.5. The ThemeResolver Interface

Spring provides stylistic theming for our views.

Let’s take a look at how to configure our dispatcher to handle themes.

First, let’s set up all the configuration necessary to find and use our static theme files. We need to set a static resource location for our ThemeSource to configure the actual Themes themselves (Theme objects contain all of the configuration information stipulated in those files). Add this to AppConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
      .addResourceLocations("/", "/resources/")
      .setCachePeriod(3600)
      .resourceChain(true)
      .addResolver(new PathResourceResolver());
}
@Bean
public ResourceBundleThemeSource themeSource() {
    ResourceBundleThemeSource themeSource
      = new ResourceBundleThemeSource();
    themeSource.setDefaultEncoding("UTF-8");
    themeSource.setBasenamePrefix("themes.");
    return themeSource;
}

Requests managed by the DispatcherServlet can modify the theme through a specified parameter passed into setParamName() available on the ThemeChangeInterceptor object. Add to AppConfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Bean
public CookieThemeResolver themeResolver() {
    CookieThemeResolver resolver = new CookieThemeResolver();
    resolver.setDefaultThemeName("example");
    resolver.setCookieName("example-theme-cookie");
    return resolver;
}
@Bean
public ThemeChangeInterceptor themeChangeInterceptor() {
   ThemeChangeInterceptor interceptor
     = new ThemeChangeInterceptor();
   interceptor.setParamName("theme");
   return interceptor;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(themeChangeInterceptor());
}

The following JSP tag is added to our view to make the correct styling appear:

1
<link rel="stylesheet" href="${ctx}/<spring:theme code='styleSheet'/>" type="text/css"/>

The following URL request renders the example theme using the ‘theme’ parameter passed into our configured ThemeChangeIntercepter:

3.6. The MultipartResolver Interface

A MultipartResolver implementation inspects a request for multiparts and wraps them in a MultipartHttpServletRequest for further processing by other elements in the process if at least one multipart is found. Add to AppConfig:

1
2
3
4
5
6
7
8
@Bean
public CommonsMultipartResolver multipartResolver()
  throws IOException {
    CommonsMultipartResolver resolver
      = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(10000000);
    return resolver;
}

Now that we’ve configured our MultipartResolver bean, let’s set up a controller to process MultipartFile requests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Controller
public class MultipartController {
    @Autowired
    ServletContext context;
    @PostMapping("/upload")
    public ModelAndView FileuploadController(
      @RequestParam("file") MultipartFile file)
      throws IOException {
        ModelAndView modelAndView = new ModelAndView("index");
        InputStream in = file.getInputStream();
        String path = new File(".").getAbsolutePath();
        FileOutputStream f = new FileOutputStream(
          path.substring(0, path.length()-1)
          + "/uploads/" + file.getOriginalFilename());
        int ch;
        while ((ch = in.read()) != -1) {
            f.write(ch);
        }
        f.flush();
        f.close();
        modelAndView.getModel()
          .put("message", "File uploaded successfully!");
        return modelAndView;
    }
}

We can use a normal form to submit a file to the specified endpoint. Uploaded files will be available in ‘CATALINA_HOME/bin/uploads’.

3.7. The HandlerExceptionResolver Interface

Spring’s HandlerExceptionResolver provides uniform error handling for an entire web application, a single controller, or a set of controllers.

To provide application-wide custom exception handling, create a class annotated with @ControllerAdvice:

1
2
3
4
5
6
7
8
9
@ControllerAdvice
public class ExampleGlobalExceptionHandler {
    @ExceptionHandler
    @ResponseBody
    public String handleExampleException(Exception e) {
        // ...
    }
}

Any methods within that class annotated with @ExceptionHandler will be available on every controller within dispatcher’s area of responsibility.

Implementations of the HandlerExceptionResolver interface in the DispatcherServlet’s ApplicationContext are available to intercept a specific controller under that dispatcher’s area of responsibility whenever @ExceptionHandler is used as an annotation, and the correct class is passed in as a parameter:

1
2
3
4
5
6
7
8
9
@Controller
public class FooController{
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {
        // ...
    }
    // ...
}

The handleException() method will now serve as an exception handler for FooController in our example above if either exception CustomException1 or CustomException2 occurs.

Here’s an article that goes more in depth about exception handling in a Spring web application.

 4. Conclusion

In this tutorial, we’ve reviewed Spring’s DispatcherServlet and several ways to configure it.

As always, the source code used in this tutorial is available over on Github.