Serialization and Deserialization
// Java code for serialization and deserialization
// of a Java object
// Serialization in Java is a mechanism that is used in converting the state of an object
// into a byte stream.
import java.io.*;
class Demo implements Serializable{
public int a;
public String b;
// constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}
class TestSerial{
public static void main(String[] args)
{
Demo object = new Demo(1, "WebProgramming");
String filename = "file.ser";
// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized");
catch(IOException ex)
{
System.out.println("IOException is caught");
}
Demo object1 = null;
// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
object1 = (Demo)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized ");
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}
catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}
}
}
Output:
What is the Transient keyword in Java?
Transient is a variable modifier that is used for serialization. Now, what is Serialization? Serialization
in Java is a mechanism that is used in converting the state of an object into a byte stream. At the time of
serialization, if you don’t want to save the value of a particular variable in a file, then use the transient
keyword.
In case you define any data member as transient, it will not be serialized. This is because every field marked
as transient will not be serialized. You can use this transient keyword to indicate the Java virtual machine
(JVM) that the transient variable is not part of the persistent state of an object.
Let’s write a very basic example to understand about Transient in Java.
class Demo implements Serializable
{
// Making human transient
private transient String human;
transient int age;
// serialize other fields
private String name, address;
Date dob;
// rest of the code
}
Here, I created a class called Demo which implements Serializable. The age data member of the Demo class
is declared as transient, its value will not be serialized. But if you deserialize the object, you will get the
default value for a transient variable.
Example 2:
// Java code for serialization and deserialization
// of a Java object
import java.io.*;
class Emp implements Serializable {
private static final long serialversionUID = 129348938L;
transient int a;
static int b;
String name;
int age;
// constructor
public Emp(String name, int age, int a, int b)
{
this.name = name;
this.age = age;
this.a = a;
this.b = b;
}
public class TestSerial2{
public static void printdata(Emp object1)
{
System.out.println("name = " + object1.name);
System.out.println("age = " + object1.age);
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}
public static void main(String[] args)
{
Emp object = new Emp("ab", 20, 2, 1000);
String filename = "Serial.txt";
// Serialization
try {
// Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);
// Method for serialization of object
out.writeObject(object);
out.close();
file.close();
System.out.println("Object has been serialized\n" + "Data before
Deserialization.");
printdata(object);
// value of static variable changed
object.b = 2000;
}
catch (IOException ex) {
System.out.println("IOException is caught");
}
object = null;
// Deserialization
try {
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);
// Method for deserialization of object
object = (Emp)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized\n" + "Data after
Deserialization.");
printdata(object);
catch (IOException ex) {
System.out.println("IOException is caught");
}
catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException" +
" is caught");
}
}
}
Output
Description for Output: You have seen while de-serializing the object the values of “a” and “b” have changed. The
reason was that “a” was marked as transient and “b” was static.
In the case of transient variables: A variable defined with a transient keyword is not serialized during the serialization
process. This variable will be initialized with the default value during deserialization. (E.g. for objects, it is null, for int it is
0).
In the case of static Variables: A variable defined with a static keyword is not serialized during the serialization process.
This variable will be loaded with the current value defined in the class during deserialization.
Transient Vs Final:
Final variables will be participated in serialization directly by their values.
Hence declaring a final variable as transient there is no use. The compiler assigns the value to a final variable.
Declaration Output
int i=100; int j=200; 100………………………….200
transient int i=100; 0………………………….200
int j=200;
transient int i=100; 0………………………….200
transient static int j=200;
transient final int i=100; 100………………………….0
transient int j=200;
Transient final int i=100; 100………………………….200
transient static int j=200;
//ClientPpr.java
import java.io.*;
import java.net.*;
public class ClientPpr{
public static void main(String o[]){
try{
Socket s = new Socket("127.0.0.1", 2222);
System.out.println("A String 'madam' is sent to server");
InputStream is = s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os =s.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
pw.println("madam");//Sent to server.
String msg = br.readLine(); //read from server.
System.out.println(msg);
s.close();
}catch(Exception e){System.out.println(e);}
} //end main
} //end class
//ServerPpr.java
import java.io.*;
import java.net.*;
import java.lang.String;
public class ServerPpr{
public static void main(String args[]){
try{
ServerSocket ss = new ServerSocket(2222);
System.out.println("Server Ready, Waiting for connections...");
while(true){
Socket s=ss.accept();
System.out.println("Connection Established");
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
String str=br.readLine();//read from Client
System.out.println("Message read from Client: "+str);
String msg="",nstr="";char ch;
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a')
count++;
}
for (int i=0; i<str.length(); i++) {
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each char. in front of the existing string
}
if(nstr.equals(str))
msg="Palindrome string." + str + " Contains " + count + " a's.";
else
msg="Not a Palindrome string." + str + " Contains " + count + " a's.";
pw.println(msg); //sent to Client
ss.close();
} //end While
}catch(Exception e){System.out.println(e);}
} //end main
} //end Class
Output:
Threading in Java
Consider the following code in java:
// File ThreeLoopTest.java
public class ThreeLoopTest {
public static void main (String args[ ]) {
//first loop
for (int i=1; i<= 5; i++)
System.out.println(“first ” +i);
// second loop
for (int j=1; j<= 5; j++)
System.out.println(“second ” + j);
// third loop
for (int k=1; k<= 5; k++)
System.out.println(“third ” + k);
} // end main
} // end class
When the program executes, the loops are executed sequentially, one after the other. It generates the
following output. Using threading in Java we can run it simultaneously. There are two ways to implement
threading in Java:
1. Extending Thread Class 2. Implementing a Runnable interface
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public class TH extends Thread { public class TH implements Runnable {
// initiated run method for Thread // method to start Thread
public void run() public void run()
{ {
System.out.println("Thread Started..."); System.out.println("Thread Started...");
} }
public static void main(String[] args)
public static void main(String[] args) {
{ TH t = new TH();
TH t = new TH(); // initializing Thread Object
// Invoking Thread using start() method Thread tt = new Thread(t);
t.start(); tt.start();
} }
} }
Code Example using Inheritance
// File Worker.java
public class Worker extends Thread{
private String job ;
//Constructor of Worker class
public Worker (String j ){
job = j;
}
//Override run() method of Thread class
public void run ( ) {
for(int i=1; i<= 10; i++)
System.out.println(job + " = " + i);
}
} // end class
// File ThreadTest.java
public class ThreadTest{
public static void main (String args[ ]) {
//instantiate three objects of Worker (Worker class is now
//becomes a Thread because it is inheriting from it)class
Worker first = new Worker (“first job”);
Worker second = new Worker (“second job”);
Worker third = new Worker (“third job”);
//start threads to execute
first.start();
second.start();
third.start();
}//end main
} // end class
Code Example using Interface
// File Worker.java
public class Worker implements Runnable {
private String job ;
//Constructor of Worker class
public Worker (String j ){
job = j;
}
//Implement run() method of Runnable interface
public void run ( ) {
for(int i=1; i<= 10; i++)
System.out.println(job + " = " + i);
}
} // end class
// File ThreadTest.java
public class ThreadTest{
public static void main (String args[ ]){
//instantiate three objects
Worker first = new Worker (“first job”);
Worker second = new Worker (“second job”);
Worker third = new Worker (“third job”);
//create three objects of Thread class & passing worker
//(runnable) to them
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
Thread t3 = new Thread (third);
//start threads to execute
t1.start();
t2.start();
t3.start();
}//end main
} // end class
Write a program in which a thread will be created. This thread will take a
positive number as input from the main thread and display all numbers from 0
to that number.
*/
import java.util.Scanner;
class Mt {
public static void main(String args[]) {
int num;
System.out.println("Enter a Number: ");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
if(num > 0) {
PrintNum obj1 = new PrintNum();
obj1.start();
obj1.run(num);
} else {
System.out.println("Number must be positive!");
}/* condition ends */
}
}
//Thread
class PrintNum extends Thread {
public void run(int num) {
for(int i = 0; i <= num; i++) {
System.out.println("Number : " + i);
}
}
}
/*
Write a program in which a thread will be created. This thread will take a
positive number as input from the main thread and display all odd numbers from 0
to that number.
*/
import java.util.Scanner;
class Mt {
public static void main(String args[]) {
int num;
System.out.println("Enter a Number : ");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
if(num > 0) {
PrintNumThread obj = new PrintNumThread();
//starting the thread
obj.start();
//calling the run method inside the thread with the argument
//'num' from the main thread
obj.run(num);
} else {
System.out.println("Number must be positive!");
}
}//End main
}//End Class
//Thread
class PrintNumThread extends Thread{
public void run(int num) {
for(int i = 0; i <= num; i++) {
if(i % 2 != 0)
System.out.println("Number: " + i);
} //End for
} //End function run()
}//End Class