Transient in Java with example
What is Transient ?
Transient is a keyword used to prevent object from serialization.
what is serialization ?
Serialization is nothing but storing the object states.
Is transient applicable for variable, method and class ?
No. transient can be used only for instance variable and
It can not be used for,
- Local variables
- Methods and
- Classes.
Transient Example program:
[java]
package com.ngdeveloper.com;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class FindEMI implements Serializable{
private transient int principal;
private transient double interest;
private transient int month;
private double emiPerMonth;
public FindEMI (int loanAmount,double rateOfInterest,
int numberOfMonths){
this.principal = loanAmount;
this.interest = rateOfInterest;
this.month = numberOfMonths;
double temp = 1200; //100*numberofmonths(12))
double interestPerMonth = rateOfInterest/temp;
double onePlusInterestPerMonth = 1 + interestPerMonth;
double powerOfOnePlusInterestPerMonth = Math.pow(onePlusInterestPerMonth,numberOfMonths);
double powerofOnePlusInterestPerMonthMinusOne = powerOfOnePlusInterestPerMonth-1;
double divides = powerOfOnePlusInterestPerMonth/powerofOnePlusInterestPerMonthMinusOne;
double principleMultiplyInterestPerMonth = loanAmount * interestPerMonth;
double totalEmi = principleMultiplyInterestPerMonth*divides;
double finalValue = Math.round( totalEmi * 100.0 ) / 100.0;
this.emiPerMonth = finalValue;
}
public void valueDisplay(){
System.out.println("Amount : " + this.principal);
System.out.println("Interest : " + this.interest);
System.out.println("Months : " + this.month);
System.out.println("EMI per month : " + this.emiPerMonth);
}
}
public class JavaTransient{
public static void main(String args[]) throws Exception {
FindEMI emiObjWrite = new FindEMI(200000,13.5,84);
ObjectOutputStream oos = new ObjectOutputStream
(new FileOutputStream("D:\\emiSerialize.txt"));
oos.writeObject(emiObjWrite);
oos.close();
ObjectInputStream ois =new ObjectInputStream(
new FileInputStream("D:\\emiSerialize.txt"));
FindEMI emiObjRead = (FindEMI)ois.readObject();
emiObjRead.valueDisplay();
}
}
[/java]
Output:
Amount : 0
Interest : 0.0
Months : 0
EMI per month : 3692.98
Amount, Interest and Months are 0, since these three variables are declared as transient.
If you remove the transient keyword then you can get the ouput like this,
Amount : 200000
Interest : 13.5
Months : 84
EMI per month : 3692.98
Note:
The variable which are declared as static will not be serialized by default.
Transient keyword can be used for static instance variable as well, but it does not make any sense.