0% found this document useful (0 votes)
41 views4 pages

Java Serialization and Externalization Guide

Serialization is the process of converting a Java object into a byte stream that can be saved or transferred. To be serialized, a class must implement the Serializable interface. Deserialization is the reverse process - taking the byte stream and recreating the original object. Externalization allows customizing the serialization process by giving the programmer control over reading and writing objects through the Externalizable interface.

Uploaded by

Karan Shah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views4 pages

Java Serialization and Externalization Guide

Serialization is the process of converting a Java object into a byte stream that can be saved or transferred. To be serialized, a class must implement the Serializable interface. Deserialization is the reverse process - taking the byte stream and recreating the original object. Externalization allows customizing the serialization process by giving the programmer control over reading and writing objects through the Externalizable interface.

Uploaded by

Karan Shah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

What is Serialization

Serialization is the conversion of a Java object into a static stream (sequence) of


bytes, which we can then save to a database or transfer over a network.

Classes that are eligible for serialization need to implement a special marker
interface, Serializable. The JVM allows special privileges to the class which
implements the Serializable Interface.

Byte stream is platform-independent. This means that once you have a stream of
bytes you can convert it into an object and run it on any kind of environment.

A class to be serialized successfully, two conditions must be met −

The class must implement the [Link] interface.


All of the fields in the class must be serializable. If a field is not
serializable, it must be marked transient.
static fields belong to a class (as opposed to an object) and are not serialized

What is Deserialization
Deserialization is precisely the opposite of serialization. With deserialization,
you start with a byte stream and re-create the object you previously serialized in
its original state. However, you must have the definition of the object to
successfully re-create it.

FileInputStream fileIn = new FileInputStream("/tmp/[Link]");


ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) [Link]();
[Link]();
[Link]();

What is Externalization?
Externalization in Java is used whenever you need to customize the serialization
mechanism.

In serialization, the Java Virtual Machine is totally responsible for the process
of writing and reading objects. This is useful in most cases, as the programmers do
not have to care about the underlying details of the serialization process.
However, the default serialization does not protect sensitive information such as
passwords and credentials, or what if the programmers want to secure some
information during the serialization process?

Thus externalization comes to give the programmers full control in reading and
writing objects during serialization. JVM has no control over it. The complete
serialization control goes to the application.

Based on our requirements, we can serialize either the whole data field or a piece
of the data field using the externalizable interface which can help to improve the
performance of the application.

Externalizable interface internaly extends Serializable interface

Externalizable interface is not a marker interface like Serializable interface. So,


it provides two methods that are as follows:

void readExternal(ObjectInput inStream) - we call readExternal() method when we


want to read an object’s fields from a stream. We need to write logic to read an
object’s fields inside the readExternal() method. The readExternal() method throws
IOException when an I/O error occurs. If the class of object being restored does
not find, ClassNotException will be thrown.

void writeExternal(ObjectOutput outStream): writeExternal() method is used when we


want to write an object’s fields to a stream. We need to write the logic to write
data fields inside writeExternal() method. This method can throw an IOException
when an I/O error occurs.

Git and Github

Git is a version control system for tracking changes in computer files and
coordinating work on those files among multiple people. It is primarily used for
source code management in software development, but it can be used to keep track of
changes in any set of files. As a distributed revision control system it is aimed
at speed, data integrity, and support for distributed, non-linear workflows.

JAVA 8 NEW FEATUREAS

WHY JAVA 8?
->Significant reason for introducing Java 8 was to introduce Conciseness in code

->Java brings in functional programming which is enabled by Lambda expression(a


powerful tool to create concise code base)

-> If you have ever observed, with python ,Scala,we can do the same thing in very
less [Link] mid 20s Java lost a large market due to some concept of FP to create
concise code base

There are lots of new features which were added in Java 8. Here is the list of
important features which are mostly asked as java 8 interview questions:

Lambda Expression
Stream API
Default methods in the interface
Functional Interface
Optional
Method references
Date API
Nashorn, JavaScript Engine

Main advantages of using Java 8?


More compact code
Less boilerplate code
More readable and reusable code
More testable code
Parallel operations

Interview question on java 8 Lambda expressions is a very commonly asked question :


Lambda expression is an anonymous function ( without name, return type and access
modifier and having one lambda symbol )

Functional interfaces are those interfaces which can have only one abstract
method .

It can have static method, default methods.

There are many functional interfaces already present in java such as eg :


Comparable, Runnable

How lambda expression and functional interfaces are related?


Lambda expressions can only be applied to abstract method of functional interface.

As we know Functional interface is an interface with Exactly One Single Abstract


method and can have multiple Static or default methods.

To create our own Functional interface, You can do following steps:


Create An interface
Annotate that with @FunctionalInterface.
Define exactly one Abstract method.
There is no restriction on number of static and default methods defined in such and
interface.

Java can implicitly identify functional interface but still you can also annotate
it with @FunctionalInterface . It just give you the security that in case if u by
mistake add 2 abstract methods then Compiler will throw compile time error.

Method Reference :
EG : MethodReferenceDemo and FunctionalInterfaceDemo

Method reference is replacement of lambda expressions. It is used to refer method


of Functional interface to an existing method. Mainly it is used for code
reusability.

Functional Interface’s Abstract method can be mapped to specific existing method


using double colon operator (::) . This is Method reference.

Hence Method reference is an alternative to Lambda expressions.

Whenever we have existing Implementation of Abstract method of our Functional


interface then we can go for method reference. If no such method like
testImplementation() is available then go for lambda expressions.

Servlet & Jsp

Servlet ::

Web Req in Servlet Scenario:

• Client Sends req to Server


• If req is dynamic Server has to take the help or Web Container/Helper
Application
○ Req will be passed to Web Container
○ Now Web Container needs to find the right Servlet to process the
request and to return the response object.
○ To find the right servlet for the req Web Container takes the help of
Deployment Descriptor or [Link] file which maps reqs to servlets
○ [Link] gives the right servlet for req
○ Now Servlet processes the req and returns a response obj most
probably as HTML page.

Servlet:
Takes the req, processes it and returns response object in most probably HTML
format.

This is basically a java class that extends httpservlet class.

Web Container:
Takes the request incase of Dynamic req and passes it to Deployment Descriptor or
[Link] file.

Eg: Tomcat, Apache etc.

Deployment Descriptor or [Link]:

Maps Requests and Servlets

Server:

Server is a computer that serves information to other computers or say clients.

Common questions

Powered by AI

To be successfully serialized, a Java class must implement the java.io.Serializable interface. Additionally, all fields in the class must be serializable. If a field is not serializable, it must be marked with the transient keyword, which prevents it from being serialized. Static fields, which belong to the class rather than any specific instance, are not serialized .

Git offers several advantages as a version control system in software development, such as speed, data integrity, and support for distributed, non-linear workflows. By storing entire repositories locally on every user's machine, Git enables collaboration without a centralized server, allowing multiple developers to work on different parts of a project simultaneously. This distributed approach enhances flexibility and facilitates branching and merging, making it easier to manage changes across complex projects and supporting collaborative development .

Externalization differs from serialization by offering the programmer full control over the serialization process. Unlike serialization, where the Java Virtual Machine handles most aspects automatically, externalization requires the programmer to explicitly define how the object's fields are written to and read from a stream. This is achieved through implementing the Externalizable interface, which provides methods like writeExternal() and readExternal(). Externalization is particularly useful for customizing the serialization process, such as protecting sensitive data or serializing only part of the object's state for performance improvements .

Method references in Java 8 are significant as they provide an alternative to lambda expressions, primarily aiming at code reusability. They allow developers to refer to methods without executing them, using the double colon (::) operator. This contributes to more readable code by enabling reuse of existing method implementations instead of rewriting logic within lambda expressions. When a functional interface's abstract method has an existing implementation, method references can be used efficiently. If such a method does not exist, lambda expressions may be necessary .

Java 8 was a significant update primarily because it introduced features that enhanced programming efficiency and encouraged a more concise codebase. Key features include lambda expressions, the Stream API, and default methods in interfaces, which collectively facilitated functional programming in Java. This transition brought Java closer to other programming languages like Python and Scala, known for their brevity and concise coding practices. These features help reduce boilerplate code, increase readability and testability, and support parallel operations in code execution .

Lambda expressions in Java 8 contribute to code compactness and readability by providing a concise way to implement anonymous functions—functions that do not require specifying a name, return type, or access modifier. They reduce boilerplate code, making the codebase more readable and maintainable. Functional interfaces, which are interfaces with a single abstract method, enable the use of lambda expressions. Lambda expressions can be applied directly to the abstract methods of these interfaces, offering a straightforward syntax that enhances code readability and reusability .

When deciding between lambda expressions and method references in Java 8, one should consider code readability, reusability, and the existence of a method implementation. Lambda expressions provide flexibility when creating short, anonymous functions without prior implementation. They are beneficial when custom logic needs to be defined in-line. Method references, however, are preferable when an existing method suits the functionality required by the functional interface, offering greater code reusability and clarity through a cleaner syntax. They simplify the code by eliminating the need to write lambda expressions when referring to existing methods, enhancing readability .

Deserialization in Java is the process of converting a byte stream back into a copy of the original object. For successful deserialization, the definition of the object's class must be available in the same form as it was during serialization. During deserialization, a byte stream is used to reconstruct the object's state, restoring it to its initial serialized form. Java's ObjectInputStream is used for this process, which reads the stream and reconstitutes the object. If the class definition is not available during deserialization, a ClassNotFoundException will be thrown, indicating an essential condition: the correct class definition must be present .

In a servlet-based web application, the web container plays a crucial role in managing dynamic requests. When a client request is received, the web container is responsible for finding the appropriate servlet to process the request. This is achieved through the deployment descriptor or web.xml file, which maps incoming requests to the corresponding servlets. Once the correct servlet is identified, the web container facilitates the execution of the servlet and returns the processed response, often in the form of an HTML page. This architecture helps in efficiently managing client-server interactions by abstracting the complexity of request handling and response generation .

Default serialization in Java is handled by the JVM, which can be convenient but may not adequately secure sensitive information such as passwords and credentials. It offers limited control over how data is serialized, posing risks of unintentional exposure. Externalization, on the other hand, allows complete control over the serialization process, enabling developers to customize how sensitive data is handled and potentially enhance security. By defining exactly which fields to serialize, developers can optimize performance by excluding unnecessary data from the serialization process, reducing overhead and increasing efficiency .

You might also like