Results 1 to 3 of 3
  1. #1
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default static in serialization

    hi friends,
    i have a doubt in serialization. i have read that static variables are not serialized.
    but when i tested it does...?

    Java Code:
    import java.io.*;
    import java.lang.Exception;
    
    class Serializer
    {
    public static void main(String ... args)
    	{
    	try
    		{
    		
    		Model obj = new Model();
    		obj.a += 10;
    		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myfile"));
    		oos.writeObject(obj);
    		oos.close();
    		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myfile"));
    		obj = (Model)ois.readObject();
    		ois.close();
    		System.out.println("a = "+obj.a);
    		System.out.println("b = "+obj.b);
    		}	
    		catch(Exception e)
    		{
    		System.out.println(e);
    		}
    	}
    
    }
    
    class Model implements Serializable
    {
    static int a = 7;
    transient int b = 11;
    }

    whats happening here?
    does static variables saved on serialization?

    thanks in advance....

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,314
    Blog Entries
    7
    Rep Power
    25

    Default

    When you instantiate a new Model, the class is loaded and initialized; you set the static member variable to 17. When an object is deserialized its class is loaded and initialized unless it already is; here the class Model is already loaded and initialized so a ends up to be equal to 17. Transient members aren't saved to the stream as you could have noticed.

    kind regards,

    Jos
    The only person who got everything done by Friday was Robinson Crusoe.

  3. #3
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

Similar Threads

  1. Replies: 7
    Last Post: 09-24-2010, 05:09 AM
  2. Replies: 3
    Last Post: 02-11-2010, 10:59 AM
  3. Replies: 0
    Last Post: 04-04-2008, 02:47 PM
  4. Replies: 1
    Last Post: 08-07-2007, 05:05 AM
  5. Replies: 1
    Last Post: 08-01-2007, 09:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •