Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Transient varialbe in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 300
    Comment on it

    We know that serialization is the process that converts java objects or data into bytes stream on one end and on other end we deserialize it that means convert bytes into orignal data.

     

    Serialization means to save data after serialization but in case when we don't want to save some data during serialization then we can use Transient variable because these variable can't be serialized.

    Example :

    public class Employee implements Serializable {
    
        private String name;
        private int id;
        private transient String comments;
        // This variable will not save data during serialization process.
    
    
        public Employee(String name, int id,String comments) {
            this.name = name;
            this.id = id;
            this.comments = comments;
        }
    
        @Override
        public String toString() {
            return "Name: " + name +
                    ", id: " + id +
                    ", comments: " + comments;
        }
    }

     

    Now from your main activity :

    Employee emp = new Employee("abc", 20,"No comments!");
    System.out.println("Before serialization:\n\t" + emp.toString());
    
            // Serialization of the object.
            try {
            FileOutputStream file = new FileOutputStream("Employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(file);
            out.writeObject(emp);
    
            System.out.printf("\emp serialized and saved.\n\n");
    
            out.close();
            file.close();
            } catch(IOException e) {
            e.printStackTrace();
            }
            // Deserialization of the object.
            try {
            FileInputStream file = new FileInputStream("Employee.ser");
            ObjectInputStream in = new ObjectInputStream(file);
            Employee st = (Employee) in.readObject();
    
            System.out.println("After serialization:\n\t" + st.toString());
    
            in.close();
            file.close();
            } catch(IOException e) {
            e.printStackTrace();
            }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: