Java Interview Questions (2023)


Core Java

public final class String extends Object implements Serializable, Comparable<String>, CharSequence

Java 8

Exceptions

Collections

THREADING

It is used in case when we want to control the number of threads accessing the resources, we can just create that many permissions.

DeadLock
LiveLock
Startvetion

YES both can run in parallel as both acquire different locks.

say request 1 can create some cookies and send it back, now request 2 might use the same cookies hence we have to be careful while using restTemplate.
SQL

A Statement is a simple SQL statement that is executed immediately, while a PreparedStatement is a precompiled SQL statement that can be reused multiple times with different parameters, resulting in faster execution times and increased security.

Precompiled in the context of a PreparedStatement means that the SQL statement is compiled by the database server before it is executed. This process involves parsing the SQL statement, checking it for syntax errors, and generating an execution plan that the database can use to efficiently execute the statement. When you create a PreparedStatement in Java, you provide the SQL statement as a parameter to the PreparedStatement constructor. The database server then compiles the SQL statement and stores it in memory so that it can be executed efficiently in the future. Because the SQL statement is precompiled, it can be executed more quickly than a regular Statement, which needs to be compiled every time it is executed. Additionally, since the database server has already checked the syntax of the SQL statement, there is less chance of encountering syntax errors at runtime. Overall, using a PreparedStatement can lead to better performance and more reliable code compared to using a regular Statement in Java.

UNION only selects distinct values, UNION ALL selects all values.

Hibernate

When we perform some action on the target entity, the same action will be applied to the associated entity. for example the Person–Address relationship, without the Person, the Address entity doesn't have any meaning of its own.
When we delete the Person entity, our Address entity should also get deleted.
    JPA Cascade Type:
  • ALL
  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DETACH
    Hibernate Cascade Type:
  • REPLICATE
  • SAVE_UPDATE
  • LOCK

Employee employee1 = session.load(Employee.class,20); //Step-1
System.out.println(employee1.getEmployeeId(); //Step-2 --o/p=20
system.out.println(employee1.getEmployeeName(); //Step-3 -->O/P:ObjectNotFoundException
If you use load in step-1 hibernate won't fire any select query to fetch employee record from DB at this moment, now at this pint hibernate gives a dummy object ( Proxy ). This dummy object doesn't contain anything, it is new Employee(20) and you can verify this in step-2 it will print 20 but in step-3 we are trying to find employee information so at this time hibernate fires a sql query to fetch Employee object. If it is not found in DB then it throws ObjectNotFoundException.

Employee employee2 = session.get(Employee.class,20); //Step-4
For session.get() hibernate fires a sql query to fetch the data from db. so in our case id=20 not exists in DB. so it will return null

Web Services

REST defines a set of architectural principles by which you can design Web services that focus on a system's resources, including how resource states are addressed and transferred over HTTP by a wide range of clients written in different languages. Roy Fielding introduced the REST architectural pattern in 2000. Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements. REST (Representational State Transfer) is basically an architectural style of development having some principles.
REST based services follow the some of the below principles and not all.
RESTFUL services means it follows all the below principles.
    REST's Architectural Constraints
  • Client-server – REST applications have a server that manages application data and state.
    The server communicates with a client that handles the user interactions.
    A clear separation of concerns divides the two components.
    This means you can update and improve them in independent tracks.
  • Stateless – Servers doesn't maintain any client state.
    Clients manage their application state.
    Their requests to servers contain all the information required to process them.
  • Cacheable –Servers must mark their responses as cacheable or non-cacheable.
    So the infrastructures and clients can cache them when possible to improve performance.
    They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – This constraint is REST's most well known feature or rule, depending on whom you ask.
    Fielding says "The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components."
    REST services provide data as resources, with a consistent namespace.
  • Layered system – Components in the system cannot "see" beyond their layer.
    So you can easily add load-balancers and proxies to improve security or performance.
  • Sessions – It does not have session.
  • HTTP verb's – For performing CRUD operations, it should use HTTP verbs such as get, post, put and delete.
    These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts.
    Also, most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.
  • URI – It should expose directory structure like URI's and it should access all the resources from the server using only URI.

PUT is an idempotent method while POST is not.
For instance calling the PUT method multiple times will either create or update the same resource. On the contrary multiple POST requests will lead to the creation of the same resource multiple times.
E.g-
POST - http://localhost:8080/addresses - Create a new resource.
PUT - http://localhost:8080/addresses/1 - Update a specific resource (by id)

Status code
Meaning
200 (OK)
This is the standard response for successful HTTP requests.
204 (NO CONTENT)
This is the standard response for successful HTTP requests, where nothing is being returned in the response body.
400 (BAD REQUEST)
The request cannot be processed because of bad request syntax, excessive size, or another client error.
403 (FORBIDDEN)
The client does not have permission to access this resource.
404 (NOT FOUND)
The resource could not be found at this time. It is possible it was deleted, or does not exist yet.
500 (INTERNAL SERVER ERROR)
The generic answer for an unexpected failure if there is no more specific information available.
Microservices

Spring

SpringBoot - It provides support for the in-memory database such as H2. Spring - It defining the dispatcher servlet, mappings, and other supporting configurations.

SpringBoot - It provides support for the in-memory database such as H2. Spring - It defining the dispatcher servlet, mappings, and other supporting configurations.

  • Singleton
  • Prototype
  • Request
  • Session
  • Websocket
  • Websocket

If more than one bean of the same type is available in the container, the framework will throw NoUniqueBeanDefinitionException, indicating that more than one bean is available for autowiring.

SpringBoot

SpringBoot - It provides support for the in-memory database such as H2. Spring - It defining the dispatcher servlet, mappings, and other supporting configurations.

In is a SpringBoot app @SpringBootApplication annotation should be in the main of the app and the class could be named something like XXXXXApplication.
Also in SpringBoot application check the pom.xml you will see starter dependencies.

Spring-boot-starter-parent
spring-boot-starter-web

  • The pattern matching for endpoints
  • OAuth 2.0
  • Form Login
  • HTTP
  • OIDC
  • Okta
  • @PreAuthorize

                                        @Min(value = 18, message = "Age should not be less than 18")
                                        Add below dependency- hibernate-validator is entirely separate from the persistence aspects of Hibernate.
                                        So, by adding it as a dependency, we're not adding these persistence aspects into the project.
                                        <dependency>
                                            <groupId>org.hibernate.validator</groupId>
                                            <artifactId>hibernate-validator</artifactId>
                                            <version>6.0.13.Final</version>
                                        </dependency>

                                        @Max(value = 150, message = "Age should not be greater than 150")
                                        private int age;

                                        @Email(message = "Email should be valid")
                                        private String email;

                                        Some other validator-
                                            @NotNull validates that the annotated property value is not null.
                                            @AssertTrue validates that the annotated property value is true.
                                            @Size validates that the annotated property value has a size between the attributes min and max;
                                            can be applied to String, Collection, Map, and array properties.
                                            @Min validates that the annotated property has a value no smaller than the value attribute.
                                            @Max validates that the annotated property has a value no larger than the value attribute.
                                            @Email validates that the annotated property is a valid email address.

                                        For Bean-When Spring finds an argument annotated with @Valid, it automatically validates the argument and
                                        throws an exception if the validation fails.
                                        @PostMapping("/register")
                                        public ResponseEntity<User> registerUser(@Valid @RequestBody RegisterUserDto registerUserDto) {
                                            User createdUser = userService.create(registerUserDto.toUser());
                                            return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
                                        }

                                        @Data
                                        public class RegisterUserDto {
                                            @NotEmpty(message = "The full name is required.")
                                            @Size(min = 2, max = 100, message = "The length of full name must be between 2 and 100 characters.")
                                            private String fullName;

                                            @NotEmpty(message = "The email address is required.")
                                            @Email(message = "The email address is invalid.", flags = { Flag.CASE_INSENSITIVE })
                                            private String email;
                                        }
                                    

Swagger
Actuator

To create a custom auto-configuration, we need to create a class annotated as @Configuration and register it.

  • Wily
  • App Dyanamics
  • Ganglia Monitoring System
  • Google tag manager

Design Patterns

System Design

Behavioral

  • Tell problem statement
  • Explain the initial approach
  • Explain problems faced during and after approach implementation?
  • Final results