Skip to main content

Java interview questions and answers for experienced (Core Java, Spring Boot, Hibernate, JPA)

 Here is a list of interview questions for the experienced guy who had more than 5 years of experience in Java, Spring Boot, Spring MVC, Hibernate, JPA. Please follow the questions bank for it.

 

  1. @component vs @service vs @repository
    • @Component: It is to mark a bean as a Spring-managed component.
      • It is a generic stereotype for any spring-managed component.
      • Spring will only pick up and register beans with @component and doesn't look for @service and @Repository
    • @service:  The @Service annotation represents that our bean holds some business logic.
    • @Repository: @Repository is a stereotype for the persistence layer and it is also a type of component. Its job is to catch all persistence-related exceptions and rethrow them as Spring DataAccessExceptions.
  2. Explain spring Bean Lifecycle
    • A Spring bean needs to be instantiated when the container starts, based on JAVA or XML bean definition.
    • It may also be required to perform some post-initialization steps to get it into a usable state.
    • After that, when a bean is no longer required, it will be removed from the loc container.
    • Spring bean factory is responsible for managing the life cycle of beans created through spring containers.
    •  Spring bean factory controls the creation and destruction of beans. To execute some custom code, it provides the call back methods which can be categorized into two groups
      • Post-Initialization
      • Pre-destruction
    • Spring framework provides the following 4 ways for controlling life cycle events of a bean
      • InitializingBean and DispoableBean call back interfaces
      • Aware interfaces for specific behavior
      • custom init() and destroy() methods in a bean configuration file
      • @PostContruct and @PreDestroy annotations.
    • @PostContruct: annotated method will be invoked after the bean has been constructed using the default constructor and just before its instance is returned to requesting object.
    • @PreDestroy: annotated method is called just before the bean is about to be destroyed inside the bean container.
  3. How you will call the @Predestory marked methods in the standalone application
    • When we annotate a Spring bean method with PreDestory annotation, it gets called when the bean instance is getting removed from the context.
    • The is a very important point to understand that if your spring bean scope is "prototype" then it isn't completely managed by spring container and PreDestory method won't get called.
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    
    public class MyBean {
    
    	public MyBean() {
    		System.out.println("MyBean instance created");
    	}
    
    	@PostConstruct
    	private void init() {
    		System.out.println("Verifying Resources");
    	}
    
    	@PreDestroy
    	private void shutdown() {
    		System.out.println("Shutdown All Resources");
    	}
    
    	public void close() {
    		System.out.println("Closing All Resources");
    	}
    }
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Scope;
    
    @Configuration
    public class MyConfiguration {
    	
        @Bean
        @Scope(value="singleton")
        public MyBean myBean() {
    	return new MyBean();
        }
    	
    }
    
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class MySpringApp {
    
    	public static void main(String[] args) {
    		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    		ctx.register(MyConfiguration.class);
    		ctx.refresh();
    
    		MyBean mb1 = ctx.getBean(MyBean.class);
    		System.out.println(mb1.hashCode());
    
    		MyBean mb2 = ctx.getBean(MyBean.class);
    		System.out.println(mb2.hashCode());
    
    		ctx.close();
    	}
    
    }
    
    
  4. What is ContextLoaderListener class in Spring?
    • ContextLoaderListener creates a root web application context for the web application and puts it is in the ServletContext.
    • This context can be used to load and unload the spring-managed beans irrespective of what technology is being in the controller layer 
  5. What are the RestClients you have used in your project?
    • You can give examples such as RestTemplate, Open Feign Client, etc.
  6. What is RestTemplate?
    • RestTemplate is a rest client to consume Restful Web services.
    • You can use the exchange() method to consume the web services for all HTTP methods.
  7. Difference getForObject() vs postForEntity()
    • getForObject()
      • The getForObject method fetches the date for the given response type from the given URI and URL template using the HTTP get method.
      URI uri = new URI("http://localhost:8080/employee");
      RestTemplate restTemplate = new RestTemplate();
      Employee[] emps = restTemplate.getForObject(uri, Employee[].class);   
    • postForEntity()
      • The getForEntity method retrieves resources from the given URI or URL templates.
      • It returns the response as ResponeEntity using which we can get response status code, response body, etc.
      public void getEmployeeDemo() throws URISyntaxException {
    		URI uri = new URI("http://localhost:8080/employee");
    
    		RestTemplate restTemplate = new RestTemplate();
    		ResponseEntity responseEntity = restTemplate.getForEntity(uri, Employee[].class);
    
    		System.out.println("Status Code: " + responseEntity.getStatusCode());
    		for (Employee e : responseEntity.getBody()) {
    			System.out.println(e);
    		}
    	}
    	
      
  8. What are the uses of ResponseEntity?
    • ResponseEntity is an extension of HttpEntity that represents an HTTP response including status, headers, and body. 
    • ResponseEntity allows you to modify the response with optional headers and status codes.
    • ResponeEntity is used when you need to change HTTP headers or HTTP status codes based on your business logic or incoming request.
      @GetMapping("/example/headers")
    public ResponseEntity exampleHeaders() {
      HttpHeaders responseHeaders = new HttpHeaders();
      responseHeaders.set("jbytecode.blogspot.com-Example-Header", "https://jbytecode.blogspot.com");
      return ResponseEntity.ok("success",).headers(responseHeaders).build();
    }
       
  9. What should be the delete API method status code?
    • For Delete Request: HTTP 200 or HTTP 204 should imply "resource deleted successfully"
    • HTTP 202 can also be returned which would imply that the instruction was accepted by the server and the "resource was marked for deletion"
  10. Why should you handle response timeout while calling any API?
    • Request timeouts are useful for preventing a poor user experience.
    • Let's say if the server doesn't respond within time, a User can no longer keep waiting for it to respond.
  11. Explain the differences between Server timeout and Read timeout.
    • The connection timeout is the timeout in making the initial connection. i.e completing the TCP connection handshake.
    • The read timeout is the timeout on waiting to read data. if the server or network fails to deliver any data with some amount of time after the client makes a socket read call, a read timeout error will be raised. 
  12. What is versioning in Rest? what are the ways that you can use to implement versioning?
    • versioning in Rest API
      • While working on an existing or creating application, we may create multiple APIs that may be consumed by many clients
      • When the business has started to grow and expand, new requirements arise.
      • Due to this. we may need to provide more functionality in the existing APIs.
      • However, existing Web APIs can be consumed by many clients. So we can avoid such problems by versioning of API.
    • There are four common ways to version a Rest API
      1. Versioning Through URI Path
        • Using the URI is the most straightforward approach.
        • It is specified in the URL as a query string.
        • For Instance, http://api.demo.com/v1
      2. Versioning through query parameters
        • This is a straightforward way of versioning an API from an implementation point of view
        • For instance: http://www.example.com/api/products?version=1
      3. Versioning through custom headers
        • a custom header allows us to preserve our URLs.
        • It is a duplicate of the content negotiation behavior implemented by the existing Accept Header.
        • Version information is specified in the Request Header without the need for any change in the URL.
        • For Instance : “Accepts-version: 1.0”
      4. Versioning through context negotiation
        • This approach allows us to version a single resource representation instead of versioning the entire API which gives us more granular control over versioning.
        • It doesn't require implementing URL routing introduced by versioning through the URI path.
        • Basically, we will provide produces/consume in the header part such as XML/JSON.
  13. Authentication vs Authorization
    • Authentication: is when an entity proves an identity.
      • In other words, Authentication proves that you are who.
      • Such as driving license
    • Authorization: is when an entity proves a right to access.
      • In other words, Authorization provide you have the right to make a request.
      • Consider the following - you have a working key card that allows you to open only some doors in the work area, but not all of them
  14. Types of authentication in Rest API
    • Types of authentication such as Basic, Bearer, OAuth, etc.
  15. What is the Bearer keyword?
    • The word Bearer provides the authorization scheme.
  16. Should you use JWT or Session-based authentication in the microservices environment?
    • JWT is used for authorization for a User. 
      • Rest API follows statelessly. It means the server will not be storing the state of your client-side.
      • So It's like it's the responsibility of the client to send all the relevant information everything in the headers.
      • So that the server is able to process that request.
      • you may have many servers/instances running in a microservice environment.
    • Session-based authentication is limited to the client-side only.
      • So other systems won't recognize your session because the current session is already built-in your local only 
  17. What are the cross-cutting concerns in spring? How do you implement it in microservices architecture?
    • Cross-cutting concerns
      • In any application, there is some generic functionality that is needed in many places exclude some applications' business logic.
      • For Instance,  you perform a role-based security check before every business method in your application. 
      • Here security is a cross-cutting concern. 
      • It is required for any application but it is not necessary from the business point of view, it is a simple generic functionality we have to implement in many places in the application. 
      • The following are examples of the cross-cutting concerns for the enterprise application.
        • Logging and tracing 
        • Transaction management 
        • Security 
        • Caching 
        • Error handling 
        • Performance monitoring 
        • Custom business rules
    • For microservice, it is best practice to implement at the API-GATEWAY level for cross-cutting concerns.
  18. How hashmap works internally?
    • HashMap uses its static inner class Node<K, V> for storing map entries. That means each entry in hashMap is a Node. Internally HashMap uses a hashCode of the key Object and this hashCode is further used by the hash function to find the index of the bucket where the new entry can be added.
    • HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored.
    • Once the bucket is identified by the hash function using hashcode, then hashCode is used to check if there is already a key with the same hashCode or not in the bucket(singly linked list).
    • If a key already exists with the same hashCode, then the equals() method is used on the keys. If the equals method returns true, that means there is already a node with the same key and hence the value against that key is overwritten in the entry(node), otherwise, a new node is created and added to this Singly Linked List of that bucket.
    • If there is no key with the same hashCode in the bucket found by the hash function then the new Node is added into the bucket found.
  19. Difference between List and Set
  20. List Set
    The list implementation allows us to add the same or duplicate elements. The set implementation doesn't allow us to add the same or duplicate elements.
    The insertion order is maintained by the List. It doesn't maintain the insertion order of elements.
    The list allows us to add any number of null values. The set allows us to add at least one null value to it.
    The List implementation classes are LinkedList and ArrayList. The Set implementation classes are TreeSet, HashSet, and LinkedHashSet.
    We can get the element of a specified index from the list using the get() method. We cannot find the element from the Set based on the index because it doesn't provide any get method().
    It is used when we want to frequently access the elements by using the index. It is used when we want to design a collection of distinct elements.
    The method of List interface listiterator() is used to iterate the List elements. The iterator is used when we need to iterate the Set elements.
  21. List practical question
    • Let's say I have initialized ArrayList with a size of 2 and if you will try to add a third element in ArrayList
    • then ArrayList will add because it will increase size dynamically.
        List strList = new ArrayList<>(2);
        strList.add("ABC");
        strList.add("DEF");
        strList.add("HIF");    
        
  22. How ArrayList works internally
    • ArrayList uses an Array of Objects to store the data internally.
    • When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 
    • 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
    • When adding a new element, if the array is full, then a new array of 50% more the initial size is created and the last array is copied to this new array so that now there are empty spaces for the new element to be added.
  23. Difference Between Fail Fast and Fail-Safe Iterators
  24. Base of Comparison Fail Fast Iterator Fail Safe Iterator
    Exception It throws a ConcurrentModificationException in modifying the object during the iteration process. It does not throw an Exception.
    Clone Object No clone object is created during the iteration process. A copy or clone object is created during the iteration process.
    Memory utilization It requires low memory during the process. It requires more memory during the process.
    Modification It does not allow modification during iteration. It allows modification during the iteration process.
    Performance It is fast. It is slightly slower than Fail Fast.
    Examples HashMap, ArrayList, Vector, HashSet, etc CopyOnWriteArrayList, ConcurrentHashMap, etc.
  25. What are the types of scope in Spring?
    • Singleton
      • only one instance of the spring bean will be created for the spring container. 
      • This is the default spring bean scope. While using this scope, make sure bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues
    • Prototype
      • A new instance will be created every time the bean is requested from the spring container.
    • Request
      • This is the same as the prototype scope, however, it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
    • Session
      • A new bean will be created for each HTTP session by the container.
  26. Difference between Hibernate and JDBC
  27. JDBC Hibernate
    In JDBC, one needs to write code to map the object model’s data representation to the schema of the relational model. Hibernate maps the object model’s data to the schema of the database itself with the help of annotations
    JDBC enables developers to create queries and update data to a relational database using the Structured Query Language (SQL). Hibernate uses HQL (Hibernate Query Language) which is similar to SQL but understands object-oriented concepts like inheritance, association, etc.
    JDBC code needs to be written in a try-catch block as it throws checked exceptions (SQLexception). Whereas Hibernate manages the exceptions itself by marking them as unchecked.
    JDBC is database dependent i.e. one needs to write different codes for different databases. Whereas Hibernate is database independent and the same code can work for many databases with minor changes.
    Creating associations between relations is quite hard in JDBC. Associations like one-to-one, one-to-many, many-to-one, and many-to-many can be acquired easily with the help of annotations.
  28. Session VS Sessionfactory 
    • SessionFactory is a factory class for Session objects. It is available for the whole application while a Session is only available for particular transactions.
    • Session is short-lived while SessionFactory objects are long-lived. SessionFactory provides a second-level cache and Session provides the first-level cache
  29. Can you create multiple session factory objects?
    • Usually, one session factory should be created for one database.
    • When you have multiple databases in your application you should create multiple SessionFactory objects.
  30. What is Persistence Context?
    • A persistence context handles a set of entities that hold data to be persisted in some persistence store (e.g. a database).
    •  In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.
    • Each EntityManager instance is associated with a persistence context.
  31. Explain the first level of caching in Hibernate.
    • The first-level cache is always Associated with the Session object. 
    • Hibernate uses this cache by default. 
    • Here, it processes one transaction after another one, which means won't process one transaction many times. 
    • Mainly it reduces the number of SQL queries it needs to generate within a given transaction. 
    • That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
  32. Explain the second level of caching in Hibernate.
    • The second-level cache is always associated with the Session Factory object. 
    • While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to a single user. 
    • Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way, the second-level cache works. Here we can use query level cache also.
  33. Difference between get() and load() in Hibernate
  34. get() load()
    It  is used to fetch data from the database for the given identifier It  is also used to fetch data from the database for the given identifier
    If objects are not found for the given identifier then it will return a null object It will throw object not found exception
    It returns a fully initialized object so this method is eager load the object. It always returns a proxy object so this method is lazy load the object
    It is slower than load() because it returns a fully initialized object which impacts the performance of the application It is slightly faster.
    If you are not sure that the object exists then use get() method. If you are not sure that the object exists then use get() method.
  35. What are detached, persistent, and transient objects in hibernate?
    • Transient - Objects instantiated using the new operator are called transient objects.
      • An object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. 
      • It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore.
    • Persistent - An object that has a database identity associated with it is called a persistent object.
      • A persistent instance has a representation in the database and an identifier value. 
      • It might just have been saved or loaded; however, it is by definition in the scope of a Session. 
      • Hibernate will detect any changes made to an object in a persistent state and synchronize the state with the database when the unit of work completes.
    • Detached - A detached instance is an object that has been persistent, but its Session has been closed.
      • A detached instance can be reattached to a new Session at a later point in time, making it persistent again. 
      • This feature enables a programming model for long-running units of work that require user think-time. 
      • We call them application transactions, i.e., a unit of work from the point of view of the user.
  36. Why do we need a connection pool?
    • Creating connections is costly and it doesn't make sense to create a new connection for each transaction that might only take a few milliseconds. 
    • Managing database connections in a pool means that applications can perform database transactions in a way that avoids the connection creation time (The connections still need to be created, but they are all created at startup). The downside is that if all connections are in use, and another connection is required, the requesting thread will have to wait until a connection is returned to the pool.
  37. What is a @GeneratedValue annotation? Explain the different generation types available in JPA.
    • @GeneratedValue: 
      • The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example, when using Mysql, you may specify auto_increment in the definition of the table to make it self-incremental.
    • There are  four types of generation types 
      • The Auto Strategy
        • It maintains a special global number generator for every database.
        • This number generator is used to generate automatic object IDs for entity objects with no primary key fields defined.
             @Entity
             public class EntityWithAutoId1 {
                @Id @GeneratedValue(strategy=GenerationType.AUTO) long id;
             }
      • The Identity Strategy
        • The IDENTITY strategy is very similar to the AUTO strategy.
        • The IDENTITY strategy also generates an automatic value during commit for every new entity object. The difference is that a separate identity generator is managed per type hierarchy, so generated values are unique only per type hierarchy.
      • The Sequence Strategy
        • The SEQUENCE is the most preferred way to generate primary key values and uses a database sequence to generate unique values.
        • It requires additional select statements to get the next value from a database sequence. But this has no performance impact for most applications.
         @Entity
        // Define a sequence - might also be in another class:
        @SequenceGenerator(name="seq", initialValue=1, allocationSize=100)
        public class EntityWithSequenceId {
            // Use the sequence that is defined above:
            @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
            @Id long id;
        }
        
      • The Table Strategy
        • The TABLE gets only rarely used nowadays.
        • It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into sequential order. 
        • This slows down your application, and you should, therefore, prefer the GenerationType.SEQUENCE, if your database supports sequences, which most popular databases do.
  38. Explain the advantages of Named Queries in Hibernate
    • compiled and validated at app start-up time
    • easier to maintain than string literals embedded in your code
    • HQL and native SQL queries can be used and replaced without code changes.
  39. What is the criteria API in hibernate? Explain the advantage.
    • allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.
    • Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max(), etc. 
    • Criteria API can be used with ProjectionList to fetch selected columns only. 
    • Criteria API can be used for joining queries by joining multiple tables, Some useful methods are createAlias(), setFetchMode(), and setProjection() 
    • Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions. 
    • Criteria API provides addOrder() method that we can use for ordering the results.
Practical Questions 
  1. Take multiple strings as input and sort that values like
    • Group string by their first character
    • Sort group by alphabetical
    • Input - "Connecticut", "Kansas", "Colorado", "Hawaii", "Alaska", "Maine", "Arkansas", "California", "Maryland","Kentucky[E]","Massachusetts[E]","Arizona", "Alabama"
    • Output - "California", "Colorado", "Connecticut", "Kansas", "Kentucky[E]", "Hawaii", "Alabama","Alaska",
      "Arizona","Arkansas","Maine","Maryland","Massachusetts[E]"
    
      
    import java.util.*;
    import java.util.stream.Collectors;
    
    import static java.lang.System.out;
    import static java.util.stream.Collectors.groupingBy;
    
    public class DS {
    
        public static void main(String[] args) {
            String str = "Connecticut,Kansas,Colorado,Hawaii,Alaska,Maine,Arkansas,California,Maryland,Kentucky[E],Massachusetts[E],Arizona,Alabama";
            List stringList = new ArrayList<>(Arrays.asList(str.split(",")));
            LinkedHashMap> linkedHashMap = stringList.stream().collect(groupingBy(o -> o.charAt(0), LinkedHashMap::new, Collectors.toList()));
            LinkedHashMap> hashMap = linkedHashMap.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
            out.println(hashMap);
        }
    }
      

Popular posts from this blog

Replace Email Template Using Java Pattern and Matcher Class

Let's say you have some simple email template that contains details like email address, phone/mobile or activation link, etc and you want to generate an email template without any free marker dependency using Java Pattern and Matcher class. So let's try to make that and also download a link is given bottom side. Step 1:    Here I created one email template which HTML code looks below. Hi {{user.first_name}} {{user.last_name}}, Welcome and thank you for subscribing. Now that you’ve subscribed, you’ll be receiving our emails {{freq.duration}}. These emails will contain our most recent article or news. You will also receive exclusive offers, promotions, and information on events. Our team is happy to have you on board. If you have any questions or comments, please don’t hesitate to contact us. You can simply reply to our emails or contact me directly using the contact information below. Thanks again! Step 2:  As you can see...

Java Collections Interview Q&A List

 The collection framework is the most important concept in java programming. It is necessary that you should have strong knowledge of the Collection framework. Through this article, I will share the topmost interview question and answers that will definitely help you in clearing your interview with flying colors. 1). What is the collection in java? List down interfaces and classes. The Collection is a set framework of interfaces and classes that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on data such as searching, sorting, insertion, manipulation, and deletion. 2).  What are the advantages of the Collection framework? Feature Description Performance The collection framework provides highly effective and efficient data structures that result in enhancing the speed and accuracy of a program. Maintainability The code developed ...