Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

transient

Example

The transient keyword is used to indicate that an attribute should not be included in the serialization process.

import java.io.*;
public class Main {
public static void main(String[] args) {
  
Person person = new Person();
   person.fname =
"John";
   person.lname =
"Doe";
   person.age = 24
;
   person.accessCode = 5044
;
    // Serialize the object
   
ByteArrayOutputStream output = new ByteArrayOutputStream();
   
try{
    
ObjectOutputStream objOut = new ObjectOutputStream(output);
     objOut.
writeObject(person);
  
} catch (IOException e) {}
    // Deserialize the object
  
Person person2 = new Person();
  
try {
  
ObjectInputStream objIn = new ObjectInputStream(newByteArrayInputStream(output.toByteArray())); 
   person2 = (Person)objIn
.readObject(); 
   } catch(Exception e) {}
    // Print the deseralized object
  
System.out.println("First name: " + person2.fname);
  
System.out.println("Last name: " + person2.lname);
  
System.out.println("Age: " + person2.age);
  
System.out.println("Access code: " + person2.accessCode);
  }
}
 class Person implements Serializable {
String fname = "John";
String lname = "Doe";
int age = 24;
transient int accessCode = 0;
}

Definition and Usage

The transient keyword is a modifier that tells Java to ignore an attribute when serializing an object.