Sunday, March 26, 2023

Interview Questions for experienced

 

  1. Explain Singleton Design Pattern?

Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category. From the definition, it seems to be a straightforward design pattern, but when it comes to implementation, it comes with a lot of concerns.

Singleton Pattern Principles

  • Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java Virtual Machine.
  • The singleton class must provide a global access point to get the instance of the class.
  • Singleton pattern is used for logging, drivers objects, caching, and thread pool.
  • Singleton design pattern is also used in other design patterns like Abstract FactoryBuilderPrototypeFacade, etc.
  • Singleton design pattern is used in core Java classes also (for example, java.lang.Runtimejava.awt.Desktop).

Java Singleton Pattern Implementation

To implement a singleton pattern, we have different approaches, but all of them have the following common concepts.

  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for the outer world to get the instance of the singleton class.

 For more details, please check https://teachtojava.blogspot.com/2016/07/singleton-design-pattern-in-java.html 

2. what are the scope of spring bean?

There are five types of spring bean scopes:

  1. 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.
  2. prototype – A new instance will be created every time the bean is requested from the spring container.
  3. request – This is same as 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.
  4. session – A new bean will be created for each HTTP session by the container.
  5. global-session – This is used to create global session beans for Portlet applications.

  1. Which Annotations are used in Spring & Spring Boot?

Spring Boot Annotations like

  1. @Bean - The @Bean annotations are used at the method level and indicate that a method produces a bean that is to be managed by the Spring container
  2. @Service- It is used at the class level. It shows that the annotated class is a service class, such as business basic logic, and call external APIs.
  3. @Repository - It is a Data Access Object (DAO) that accesses the database directly. It indicates that the annotated class is a repository. 
  4. @Configuration - It is used as a source of bean definitions. It is a class-level annotation, The configuration annotation represents the class having one or more @Bean methods. The spring container could go ahead and generate the Spring Beans to be used.
  5. @Controller - The annotation is used to indicate that the class is a web request handler. It is often used to present web pages. It is most commonly used with @RequestMapping annotation. 
  6. @RequestMapping - RequestMapping is used to map the HTTP request. It is used with the class as well as the method. It has many other optional elements like consumes, name, method, request, path, etc.
  7. @Autowired - This annotation is used to auto-wire spring bean on setter methods, constructor and instance variable. It injects object dependency implicitly. When we use this annotation, the spring container auto-wires the bean by its matching data type. The Autowired annotation is used to inject the dependency in the bean. The Autowired provides more control to the developers over where the Autowire should be used.
  8. @Component - It is a class-level annotation that turns the class into Spring bean at the auto-scan time. The component annotation can automatically detect custom beans. It represents that the framework could autodetect these classes for dependency injection
  9. @SpringBootApplication - It consists of @Configuration, @ComponentScan, and @EnabeAutoConfiguration. The class annotated with @SpringBootApplication is kept in the base package. This annotation does the component scan. However, only the sub-packages are scanned. The SpringBoot Application mark a configuration class that declares Bean methods, either one or more than that. The Spring Boot Application contains-
  1. Auto-configuration
  2. Spring Boot Configuration
  3. Component Scan

 

1 @EnableAutoConfiguration

It is placed on the main application class. Based on classpath settings, other beans, and various property settings, this annotation instructs SpringBoot to start adding beans.

The Enable Auto Configuration allows the spring boot to auto-figure the application context. The applications are auto figured basis the added jar dependencies.

11@ComponetScan

It is used to scan a package of beans. It is used with the annotation @Configuration to allow Spring to know the packages to be scanned for annotated components. This annotation is also used to specify base packages.

 

12@Required

This annotation is applied to bean setter methods. It indicates that the required property must be filled at the configuration time in the affected bean, or else it throws an exception: BeanInitializationException.

13.  @Qualifier

It is used along with @Autowired annotation. It is used when more control is required over the dependency injection process. Individual constructor arguments or method parameters can be specified by using this annotation. Confusion arises when more than one bean of the same type is created, and only one of them is to be wired with a property, @Qualifier is used to get rid of the confusion.

@Lazy

It is used in the component class. At startup, all auto-wired dependencies are created and configured. But a @Lazy annotation can be created if a bean is to be initialized lazily. This means that only if it is requested for a bean will be created. It can also be used on @Configuartion classes. It’s an indication that all @Bean methods within that @Configuration should be lazily initialized.


  1. What is method overriding?

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).

 

  1. What are the Java 8 features

Java 8 provides following features for Java Programming:

  • Lambda expressions,
  • Method references,
  • Functional interfaces,
  • Stream API,
  • Default methods,
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
  • ForEach() method,
  • Nashorn JavaScript Engine,
  • Parallel Array Sorting,
  • Type and Repating Annotations,
  • IO Enhancements,
  • Concurrency Enhancements,
  • JDBC Enhancements etc.

 

 

  1. Difference between functional interface and abstract class

https://teachtojava.blogspot.com/2016/08/difference-between-abstract-class-and.html


  1. Difference between filter & map

 

Both of these methods are present in Stream API and which is used to perform sequential and parallel operations. Apart from this point, these two methods are intermediate operations and return a Stream as a result.

 

Note: map() and filter() methods can be invoked on a single stream. There is no restriction to use the only operation at a time.

 

he following are the differences and similarities of map() and filter() methods.

Stream map()


A) map() operation is part of Stream API.
B) map() is an Intermediate Operation.
C) map() method takes as an argument Function functional interface and Function implementation will return the same as input or different type.
D) map() returns a Stream<T>

E) map() method returned Stream preserves the order of how they appear in the original list or Stream.
F) All values in the stream must be traversed through the logic of the Function function interface. (map() logic)
G) This will be returning a value which is mandatory. If not returning will result in a compile-time error.
H) map() method will always transform the current value or object into another type or same type. If we do not want to pass the value to the next step then we need to return a null value from the map() method.


Stream filter()


A) filter() operation is part of Stream API.
B) filter() is an Intermediate Operation.
C) filter() method takes as an argument Predicate functional interface and Predicate tells true or false about the predicate condition.
D) filter() returns a Stream<T>.
E) filter() method returned Stream preserves the order how they appear in the original list or Stream.
F) All values in the stream must be traversed through the logic of Predicate function interface. (filter() logic)
G) This will also be returning a value that is mandatory. If not returning will result in a compile-time error.
H) filter() method passes the values to the next step if the filter condition is true. Otherwise, the current object will be skipped from processing in the next step.

  1. Difference between filter and flat filter

The difference is that the map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value.


 

  1. Examples for functional interface?

functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. RunnableActionListener, Comparable are some of the examples of functional interfaces. 

Some Built-in Java Functional Interfaces

Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows – 

·       Runnable –> This interface only contains the run() method.

·       Comparable –> This interface only contains the compareTo() method.

·       ActionListener –> This interface only contains the actionPerformed() method.

·       Callable –> This interface only contains the call() method.

 

Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations. These are:

1.     Consumer

2.     Predicate

3.     Function 

4.     Supplier

Amidst the previous four interfaces, the first three interfaces,i.e., Consumer, Predicate, and Function, likewise have additions that are provided beneath – 

1.     Consumer -> Bi-Consumer

2.     Predicate -> Bi-Predicate

3.     Function -> Bi-Function, Unary Operator, Binary Operator 

 

  1. Difference between primary key and unique key?

The primary key is accepted as a unique or sole identifier for every record in the table. In the case of a primary key, we cannot save NULL values. In the case of a unique key, we can save a null value, however, only one NULL value is supported.

 

Comparison Chart: 

Parameter

PRIMARY KEY

UNIQUE KEY

Basic

Used to serve as a unique identifier for each row in a table.

Uniquely determines a row which isn’t primary key.

NULL value acceptance

Cannot accept NULL values.

Can accepts NULL values.

Number of keys that can be defined in the table

Only one primary key

More than one unique key

Index

Creates clustered index

Creates non-clustered index

Auto Increment

A Primary key supports auto increment value.

A unique key does not supports auto increment value.

Modification

We cannot change or delete values stored in primary keys.

We can change unique key values.

 

Difference between @PathVariable and @RequestParam in Spring

@RequestParam annotation fetch the value of request parameter in the form of passing request parameter with url but @PathVariable annotation fetching value of the parameter in the form request URI template with some placeholder.


 What is the use of @RequestBody Annotation in Spring and Spring Boot?

The @RequestBody annotation is responsible for binding the HTTPRequest body to the body of the web request. Depending on the content type of the request, the body of the request is given through a HttpMessageConverter, which resolves the method argument. 

 

We can also use the @Valid annotation to automatically validate the input.

In brief, the 
@RequestBody annotation is responsible for retrieving the request body and automatically converting it to the Java object. 

 

  1. What is lambda expression

Lambdas are similar to methods, but they do not need a name and can be implemented outside of classes. As a result, they open the possibility for fully functional programs and pave the way for more functional support from Java in the future.

The syntax of a basic lambda expression is:

parameter -> expression


  1. What is default method in java?

Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

 

The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. Default methods are also known as defender methods or virtual extension methods.

Default Methods and Multiple Inheritance
In case both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.

What is difference between Comparable and Comparator interface?
Comparable and Comparator interfaces are used to sort collection or array of objects.

  • Comparable Interface is actually from java.lang package.
  • It will have a method compareTo(Object obj)to sort objects
  • Comparator Interface is actually from java.util package.
  • It will have a method compare(Object obj1, Object obj2)to sort objects
 Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic.

Comparator interface is used to provide different algorithms for sorting and we can choose the comparator we want to use to sort the given collection of objects.


  1. Difference between monolithic & microservices

Monolithic vs Microservices architecture

In order to understand microservices, we need to understand what are monolithic applications and what led us to move from monolithic applications to microservices in recent times. 

Monolithic applications 
If all the functionalities of a project exist in a single codebase, then that application is known as a monolithic application. We all must have designed a monolithic application in our lives in which we were given a problem statement and were asked to design a system with various functionalities. We design our application in various layers like presentation, service, and persistence and then deploy that codebase as a single jar/war file. This is nothing but a monolithic application, where “mono” represents the single codebase containing all the required functionalities. 


Disadvantages of Monolithic applications: 

·       It becomes too large with time and hence, difficult to manage.

·       We need to redeploy the whole application, even for a small change.

·       As the size of the application increases, its start-up and deployment time also increases.

·       For any new developer joining the project, it is very difficult to understand the logic of a large Monolithic application even if his responsibility is related to a single functionality.

·       Even if a single part of the application is facing a large load/traffic, we need to deploy the instances of the entire application in multiple servers. It is very inefficient and takes up more resources unnecessarily. Hence, horizontal scaling is not feasible in monolithic applications.

·       It is very difficult to adopt any new technology which is well suited for a particular functionality as it affects the entire application, both in terms of time and cost.

·       It is not very reliable, as a single bug in any module can bring down the entire monolithic application.

Advantages of monolithic applications:  

·       Simple to develop relative to microservices, where skilled developers are required in order to identify and develop the services.

·       Easier to deploy as only a single jar/war file is deployed.

·       Relatively easier and simple to develop in comparison to microservices architecture.

·       The problems of network latency and security are relatively less in comparison to microservices architecture.

·       Developers need not learn different applications, they can keep their focus on one application.

Microservices 
It is an architectural development style in which the application is made up of smaller services that handle a small portion of the functionality and data by communicating with each other directly using lightweight protocols like HTTP. According to Sam Newman, “Microservices are the small services that work together.” 


The Microservice architecture has a significant impact on the relationship between the application and the database. Instead of sharing a single database with other microservices, each microservice has its own database. It often results in duplication of some data, but having a database per microservice is essential if you want to benefit from this architecture, as it ensures loose coupling. Another advantage of having a separate database per microservice is that each microservice can use the type of database best suited for its needs. Each service offers a secure module boundary so that different services can be written in different programming languages. There are many patterns involved in microservice architecture like service discovery & registry, caching, API gateway & communication, observability, security, etc.

Principles of microservices:  

·       Single responsibility: It is one of the principles defined as a part of the SOLID design pattern. It states that a single unit, either a class, a method, or a microservice should have one and only one responsibility. Each microservice must have a single responsibility and provide a single functionality. You can also say that: the number of microservices you should develop is equal to the number of functionalities you require. The database is also decentralized and, generally, each microservice has its own database.

·       Built around business capabilities: In today’s world, where so many technologies exist, there is always a technology that is best suited for implementing a particular functionality. But in monolithic applications, it was a major drawback, as we can’t use different technology for each functionality and hence, need to compromise in particular areas. A microservice shall never restrict itself from adopting an appropriate technology stack or backend database storage that is most suitable for solving the business purpose, i.e., each microservice can use different technology based on business requirements.

·       Design for failure: Microservices must be designed with failure cases in mind. Microservices must exploit the advantage of this architecture and going down one microservice should not affect the whole system, other functionalities must remain accessible to the user. But this was not the case in the Monolithic applications, where the failure of one module leads to the downfall of the whole application.

Service-oriented architecture (SOA) vs Microservices architecture: 

Steve Jones, MDM at Capgemini once said, “Microservices is SOA, for those who know what SOA is”. So, those who know about SOA, most think that they are the same, or the difference is not much clearer in their mind. We can’t blame them also, if we talk about a cake and a pastry, we will find more similarities than differences. So let’s try to understand the differences between the two. 
SOA evolved in order to deal with the problems in monolithic architecture and became popular in the early 2000s. In SOA, the large application is split up into multiple smaller services that are deployed independently. These services don’t communicate with each other directly. There used to be an Enterprise Service Bus (ESB, a middleware or server with the help of services using different protocols or message standards that can communicate with each other easily) where these services expose themselves and communicate with each other through it. Also, there was no guideline to have an independent database for each service. 

Microservices architecture is an evolution of SOA. People also consider SOA as a superset of microservices. In simple terms, microservices is a fine-grained SOA. Here, the microservices communicate with each other directly and there is no central dependency for communication such as ESB in SOA. Also, there is a guideline to have a separate database for each microservice. The fundamental idea of the evolution of microservices from SOA is to reduce the dependency between the services and make them loosely coupled with the above-mentioned guidelines. 

Advantages of microservices:  

·       It is easy to manage as it is relatively smaller.

·       If there’s any update in one of the microservices, then we need to redeploy only that microservice.

·       Microservices are self-contained and, hence, deployed independently. Their start-up and deployment times are relatively less.

·       It is very easy for a new developer to onboard the project as he needs to understand only a particular microservice providing the functionality he will be working on and not the whole system.

·       If a particular microservice is facing a large load because of the users using that functionality in excess, then we need to scale out that microservice only. Hence, the microservices architecture supports horizontal scaling.

·       Each microservice can use different technology based on the business requirements.

·       If a particular microservice goes down due to some bug, then it doesn’t affect other microservices and the whole system remains intact and continues providing other functionalities to the users.

Disadvantages of microservices:  

·       Being a distributed system, it is much more complex than monolithic applications. Its complexity increases with the increase in a number of microservices.

·       Skilled developers are required to work with microservices architecture, which can identify the microservices and manage their inter-communications.

·       Independent deployment of microservices is complicated.

·       Microservices are costly in terms of network usage as they need to interact with each other and all these remote calls result in network latency.

·       Microservices are less secure relative to monolithic applications due to the inter-services communication over the network.

·       Debugging is difficult as the control flows over many microservices and to point out why and where exactly the error occurred is a difficult task.

 

 

What Is Load Balancing in microservice architecture?

Load balancing is the process of distributing traffic among different instances of the same application.

To create a fault-tolerant system, it's common to run multiple instances of each application. Thus, whenever one service needs to communicate with another, it needs to pick a particular instance to send its request.

There are many algorithms when it comes to load balancing:

  • Random selection: Choosing an instance randomly
  • Round-robin: Choosing an instance in the same order each time
  • Least connections: Choosing the instance with the fewest current connections
  • Weighted metric: Using a weighted metric to choose the best instance (for example, CPU or memory usage)

what is use of profile in spring boot

Enterprise application development is complex. You have multiple environments

  • Dev
  • QA
  • Stage
  • Production

You want to have different application configuration in each of the environments.

Profiles help to have different application configuration for different environments.

Spring and Spring Boot provide features where you can specify

  • What is the configuration for various environments in different profiles?
  • Set the active profile for a specific environment.

Spring Boot would pick up the application configuration based on the active profile that is set in a specific environment.


 

  1. Is it allow multiple application.properties files or not in spring boot application

Spring Boot supports different properties based on the Spring active profile. For example, we can keep two separate files for development and production to run the Spring Boot application.


  1. What is use of Optional

Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.


What is the use of JUnit and Mockito?
JUnit is a framework that helps with writing and running your unit tests. Mockito (or any other mocking tool) is a framework that you specifically use to efficiently write certain kind of tests.

  1. What is agile methodology

The Agile methodology is a way to manage a project by breaking it up into several phases. It involves constant collaboration with stakeholders and continuous improvement at every stage. Once the work begins, teams cycle through a process of planning, executing, and evaluating. Continuous collaboration is vital, both with team members and project stakeholders.

Agile is an iterative approach to project management and software development that helps teams deliver value to their customers faster and with fewer headaches. Instead of betting everything on a "big bang" launch, an agile team delivers work in small, but consumable, increments. Requirements, plans, and results are evaluated continuously so teams have a natural mechanism for responding to change quickly. 

What are sprints?

 A sprint is a short, time-boxed period when a scrum team works to complete a set amount of work. Sprints are at the very heart of scrum and agile methodologies, and getting sprints right will help your agile team ship better software with fewer headaches.

What is the difference between interface and functional interface in Java,

Java interface can have any number of abstract methods however functional interface must have only one abstract method.

what is type conversion in java.

The process of converting a value from one data type to another is known as type conversion in Java. Type conversion is also known as type casting in java or simply 'casting'. If two data types are compatible with each other, Java will perform such conversion automatically or implicitly for you.


what is object class and methods in object class in java

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. The Object class is beneficial if you want to refer any object whose type you don't know

Using Object Class Methods

The Object class provides multiple methods which are as follows:

·       tostring() method

·       hashCode() method

·       equals(Object obj) method

·       finalize() method

·       getClass() method

·       clone() method

·       wait(), notify() notifyAll() methods



difference between error and exception in java

Errors and exceptions are subclasses of the Throwable Java class. The Error class represents critical conditions that can not be caught and handled by the code of the program. On the other hand, the Exception class represents concerning conditions raised by the application itself; these can be caught and handled within the code to ensure that the application continues to run smoothly.

 

Differences

The key differences between exceptions and errors are as follows:

Errors

Exceptions

Errors are usually raised by the environment in which the application is running. For example, an error will occur due to a lack of system resources.

Exceptions are caused by the code of the application itself.

It is not possible to recover from an error.

The use of try-catch blocks can handle exceptions and recover the application from them.

Errors occur at run-time and are not known by the compiler; hence, they are classified as “unchecked.”

Exceptions can be “checked” or “unchecked,” meaning they may or may not be caught by the compiler.

“OutOfMemory” and “StackOverflow” are examples of errors.

“IndexOutOfBounds” is an example of an unchecked exception, while “ClassNotFound” is an example of a checked exception.



  1. Difference between curd repository and jpa repository

CRUD Repository 

There is an interface available in Spring Boot named as CrudRepository that contains methods for CRUD operations. It provides generic Crud operation on a repository. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface. 

Syntax:

public interface CrudRepository<T, ID> extends Repository<T, ID>

JpaRepository 

JpaRepository is a JPA (Java Persistence API) specific extension of Repository. It contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting. 

Syntax:

public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>

 

CrudRepository 

JpaRepository 

It is a base interface and extends Repository Interface.

It extends PagingAndSortingRepository that extends CrudRepository.

It contains methods for CRUD operations. For example save(), saveAll(), findById(), findAll(), etc. 

It contains the full API of CrudRepository and PagingAndSortingRepository. For example, it contains flush(), saveAndFlush(), saveAllAndFlush(), deleteInBatch(), etc along with the methods that are available in CrudRepository.

It doesn’t provide methods for implementing pagination and sorting

It provides all the methods for which are useful for implementing pagination.

It works as a marker interface.

It extends both CrudRepository and PagingAndSortingRepository.

To perform CRUD operations, define repository extending CrudRepository.

To perform CRUD as well as batch operations, define repository extends JpaRepository.

Syntax: 

public interface CrudRepository<T, ID> extends Repository<T, ID>

Syntax:

public interface JpaRepository<T,ID> extends PagingAndSortingRepository<T,ID>, QueryByExampleExecutor<T>

 

  1. What is use of finalize() method

The Java finalize() method of Object class is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection, or we can say resource de-allocation. Remember, it is not a reserved keyword. Once the finalize() method completes immediately, Garbage Collector destroys that object. 

 

Why finalize() method is used? 

finalize() method releases system resources before the garbage collector runs for a specific object. JVM allows finalize() to be invoked only once per object.

How to override finalize() method? 

The finalize method, which is present in the Object class, has an empty implementation. In our class, clean-up activities are there. Then we have to override this method to define our clean-up activities.

 

  1. What is Method Signature?

Method Signature is the combination of a method's name and its parameter list. A class cannot have two methods with the same signature. If we declare two methods with the same signature, compilation error is thrown.


  1. Define LinkedHashSet

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set. That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.


  1. What is serializable why it is used?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

What is Serialization in Java?

Serialization in Java is the concept of representing an object’s state as a byte stream. The byte stream has all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there.

 

Serialization in Java is the concept of representing an object’s state as a byte stream. The byte stream has all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there.

What are the Advantages of Serialization?

Serialization offers a plethora of benefits. Some of its primary advantages are:

·       Used for marshaling (traveling the state of an object on the network)

·       To persist or save an object’s state

·       JVM independent

·       Easy to understand and customize.

 

Serialization in Java [Advantages and Examples Explained]

By Simplilearn

Last updated on Dec 12, 202221103

Serialization in Java

Table of Contents

What is Serialization in Java?

What are the Advantages of Serialization?

Points to Note About Serialization in Java?

How to Serialize an Object?

Serialization in Java With Inheritance (Is-A Relationship)

View More

This serialization in Java article will shed light on the mechanism of serialization, and its benefits. It will also explore how to serialize an object, and how to serialize using different Java concepts, with examples.

What is Serialization in Java?

Serialization in Java is the concept of representing an object’s state as a byte stream. The byte stream has all the information about the object. Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there.

Deserialization is the exact opposite process of serialization where the byte data type stream is converted back to an object in the memory. The best part about these mechanisms is that both are JVM-independent, meaning you serialize on one JVM and de-serialize on another.

What are the Advantages of Serialization?

Serialization offers a plethora of benefits. Some of its primary advantages are:

  • Used for marshaling (traveling the state of an object on the network)
  • To persist or save an object’s state
  • JVM independent
  • Easy to understand and customize

Points to Note About Serialization in Java?

To serialize an object, there are a few conditions to be met. Some other key points need to be highlighted before you proceed further in the article. These are the conditions and points to remember while using serialization in Java.

  • Serialization is a marker interface with no method or data member
  • You can serialize an object only by implementing the serializable interface
  • All the fields of a class must be serializable; otherwise, use the transient keyword (more about it later)
  • The child class doesn’t have to implement the Serializable interface, if the parent class does
  • The serialization process only saves non-static data members, but not static or transient data members
  • By default, the String and all wrapper classes implement the Serializable interface

How to Serialize an Object?

Since you now know what serialization in Java is, and all the relevant points, let’s delve deep into how to serialize an object. You must use the writeObject() method of the ObjectOutputStream class for serialization and readObject() method of the InputObjectStream class for deserialization purpose.

Syntax for the writeObject() method:

public final void writeObject(Object o) throws IO Exception

Syntax for the readObject() method:

public final Object readObject() throws IOException, ClassNotFoundException

 

what is callable interface in java

Interface Callable<V>

Implementors define a single method with no arguments called call. The Callable interface is similar to Runnable , in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

 what are features of functional interface in java

An Interface that contains exactly one abstract method is known as functional interface. It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class. Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.


How to define custom repository in Spring Data JPA?

When using Custom Repository?

Having said that, we will need to create a custom repository if using entity-bound repository interface does not work, or when we need to query data from multiple tables in which join cannot be used. In other words, use custom repository when we want to totally control the query code - not depending on the default semantics of Spring Data JPA’s repository interfaces.

Also using custom repository when you don’t want (or cannot) use the <Entity, ID> pair in the repository interface.

https://vladmihalcea.com/custom-spring-data-repository/


how to identify the log files in spring boot

Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each case, loggers are pre-configured to use console output with optional file output also available.

Now we simply need to run the application and hit http://localhost:8080/log to see the log messages

What are the exceptions in Spring Boot

The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. You can use the following code to create @ControllerAdvice class to handle the exceptions globally 


what is spring boot-starter-parent?

The spring-boot-starter-parent is a project starter. It provides default configurations for our applications. It is used internally by all dependencies. All Spring Boot projects use spring-boot-starter-parent as a parent in pom. xml file.