aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Serialization. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Serialization." Watch "Serialization." New topic
Author

Serialization.

Rohit Ramachandran
Ranch Hand

Joined: Oct 05, 2010
Posts: 102

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

public class Tester implements Serializable{

transient int x = 5;

public static void main(String[] args) {
Tester tester1 = new Tester();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("data.txt"));
os.writeObject(tester1);
os.close();
System.out.print(++tester1.x + " ");
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
"data.txt"));
Tester tester2 = (Tester) is.readObject();
is.close();
System.out.println(tester2.x);
} catch (Exception x) {
System.out.println("Exception thrown");
}
}

}

Output: 6 0

I don't get it. Why is it 0?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Please UseCodeTags when posting code. It will highlight your code and make it much easier to read. It probably will also increase the number of people helping you.

Why would it be 0? You have written the object to the file but that doesn't change anything to the object itself. Nothing gets changed. The value gets incremented and printed.

Although it is nice to know how serialization works, it is no longer on the current exam.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Komal Arora
Ranch Hand

Joined: Sep 30, 2010
Posts: 91

Transient variables are NOT serialized. tester1 is written, but as wouter said
You have written the object to the file but that doesn't change anything to the object itself. Nothing gets changed. The value gets incremented and printed.
In the second case, when you READ back the object, since the state was declared transient, the state was NOT saved and hence we get 0 as the output.


OCPJP
Rahul Saple
Ranch Hand

Joined: Aug 02, 2006
Posts: 46
Also, changing the tranisent nature of the field would lead to the answer being 5 in the desrialized output, as you are incrementing the value after it is written out to the file.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Serialization.
 
Similar Threads
Serialization for statics
what is "null"
IOException while reading objects
Serialization issue
serializable problem