Java Transient Variable

This this tutorial you will learn about the java transient variable and its use

Java Transient Variable

This this tutorial you will learn about the java transient variable and its use

Java Transient Variable

Java Transient Variables

Before knowing the transient variable you should firs know about the Serialization in java. Serialization means making a object state persistent. By default all the variables of an object becomes persistent. If you does not want to make the state of an object persistent then you can mark that object as persistent. You can also say that the transient variable is a variable whose state does not  Serialized.

An example of transient variable is given below blow, in this example the variable course is made as transient.

Student.java

import java.io.Serializable;

public class Student implements Serializable {
	private int rollNo;
	private String name;
	private transient String course;
	private String address;

	public Student() {

	}

	public Student(int rollNo, String name, String course, String address) {
		this.rollNo = rollNo;
		this.name = name;
		this.course = course;
		this.address = address;
	}

	public void detail() {
		System.out.println("Roll No :- " + this.rollNo);
		System.out.println("Name :- " + this.name);
		System.out.println("Course :- " + this.course);
		System.out.println("Address :- " + this.address);
	}

}

MainClaz.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class MainClaz {
	public static void main(String[] args) throws IOException, Exception {
		Student student = new Student(1, "Jorge", "M.Tech", "Melbourn");
		ObjectOutputStream in = new ObjectOutputStream(new FileOutputStream(
				"LogFile.text"));
		in.writeObject(student);
		in.close();
		Thread.sleep(500);
		ObjectInputStream out = new ObjectInputStream(new FileInputStream(
				"LogFile.text"));
		Student showStudent = (Student) out.readObject();
		showStudent.detail();
	}
}


When you run this application it will display message as shown below:


Roll No :- 1
Name :- Jorge
Course :- null
Address :- Melbourn

Download Select Source Code