Why Static variables not included in a serialization process

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Why Static variables not included in a serialization process

Post by schchen2000 »

In layman terms,

serialization = writing values to a file

deserialization = reading values from a file

What kind of file extensions do you allow? Every time I attach a file here, I always get "file extension not allowed" error.

Please see 2 code segments in 2 separate posts after this due to 3000-character limit. Both code segments are tested and they both work.

They are adapted from

https://www.amazon.com/OCP-Certified-Pr ... entries*=0

and I own one hard copy book.

To run them, please do

javac ObjectStreamSample.java AnimalSerializable.java

followed by

java ObjectStreamSample

Now you said
Remember that static fields are never serialized....
The book also says any static variables or default initializations are ignored.

In the 2nd code segment, createAnimalsFile() is used to serialize, i.e. to write values to a file, and getAnimals() is used to deserialize, i.e. to read values from a file.

Question 1

As you said, if the static fields are never serialized, i.e. values not written to a file, then how can we deserialize, i.e. read values from a file, by using getAnimals() method in the 2nd code segment?

Question 2

When you said "static fields are never serialized," did you mean ignoring all static fields in the process of serialization whether or not the static variables contain programmer-initialized values or the default values assigned to them by the compiler?

I'm simply trying to understand this concept. I have no other intention.

Thanks.

Schmichael
Last edited by schchen2000 on Fri Jun 03, 2016 5:07 pm, edited 1 time in total.

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

Please name this file as AnimalSerializable.java.

Code: Select all

import java.io.Serializable;

public class AnimalSerializable implements Serializable{

	private static final long serialVersionUID = 2L;

	private transient String name;

	private transient int age = 10;

	private static char type = 'C';

	private static int temp = 777;

	{this.age = 14;}

	public AnimalSerializable(){

		System.out.println("\nCalling NO ARGUMENT AnimalSerializable constructor....");

		this.name = "Unknown";

		this.age = 12;

		this.type = 'Q';

	}

	public AnimalSerializable(String name, int age, char type){

		System.out.println("\nCalling ARGUMENTED AnimalSerializable constructor....");

                this.name = name;

                this.age = age;

                this.type = type;

        }

	public String getName(){

		return name;

	}

	public int getAge(){

                return age;

        }

	public char getType(){

                return type;

        }

	public String toString(){

		return "Animal [" + "id = " + serialVersionUID + ", name = " + name + ", age = " + age + ", type = " + type + ", temp = " + temp + "]";

	}

	

}

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

Please name this file ObjectStreamSample.java.

createAnimalsFile() is used to serialize, i.e. to write values to a file, and getAnimals() is used to deserialize, i.e. to read values from a file.

Code: Select all

import java.io.*;

import java.util.*;

public class ObjectStreamSample{

	public static List<AnimalSerializable> getAnimals(File dataFile) throws IOException, ClassNotFoundException{

		List<AnimalSerializable> animals = new ArrayList<AnimalSerializable>();

		try(ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)))){

			System.out.println("\nAbout to get into while loop() to read from the file aka object deserializing....");

			while(true){

				Object object = in.readObject();

				if(object instanceof AnimalSerializable){

					System.out.println("\n" + (AnimalSerializable) object);

					animals.add((AnimalSerializable) object);

				}

			}

		}catch(EOFException e){

			System.out.println("\nEnd of reading file....");

			//File end reached

		}

		System.out.println("\nReturning a List<AnimalSerializable> from getAnimals() to main(): \n\n" + animals);

		return animals;

	}

	public static void createAnimalsFile(List<AnimalSerializable> animals, File dataFile) throws IOException{

		System.out.println("\nList<AnimalSerializable> coming from main() before object serialization: \n\n" + animals);

		try(ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)))){

			System.out.println("\nBeginning of a file population aka Object Serialization....");

			for(AnimalSerializable animal : animals){

				System.out.println("\n" + animal);

				out.writeObject(animal);

			}

			System.out.println("\nThe end of a file population aka Object Serialization....");

		}

	}

	public static void main(String... args) throws IOException, ClassNotFoundException{

		List<AnimalSerializable> animals = new ArrayList<AnimalSerializable>();

		animals.add(new AnimalSerializable("Tommy Tiger", 5, 'T'));

		animals.add(new AnimalSerializable("Peter Penguin", 8, 'P'));

		System.out.println("\nAfter List<AnimalSerializable> being populated in main(): \n\n" + animals);

		File dataFile = new File("animal.data");

		createAnimalsFile(animals, dataFile);

		System.out.println("\nDeserialization from main(): \n\n" + getAnimals(dataFile) + "\n");

	}

}

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by admin »

schchen2000 wrote:In layman terms,

serialization = writing values to a file

deserialization = reading values from a file
That is not correct. serialization means to convert an object to a byte stream. deserialization means to convert a stream of data into Java objects. It has nothing to do with reading/writing from/to a file.
What kind of file extensions do you allow? Every time I attach a file here, I always get "file extension not allowed" error.
I think only images.
Please see 2 code segments in 2 separate posts after this due to 3000-character limit. Both code segments are tested and they both work.
What do you mean by "work"? Successful compilation? Execution without any exception? or Execution as per your expectation?
Now you said
Remember that static fields are never serialized....
The book also says any static variables or default initializations are ignored.

In the 2nd code segment, createAnimalsFile() is used to serialize, i.e. to write values to a file, and getAnimals() is used to deserialize, i.e. to read values from a file.

Question 1

As you said, if the static fields are never serialized, i.e. values not written to a file, then how can we deserialize, i.e. read values from a file, by using getAnimals() method in the 2nd code segment?
Your question is not clear. When you say "how can we deserialize", do you mean you want to be able to deserialize but don't know how to? or do you see it getting deserialized but don't understand why is it getting deserialized?

It is true that static fields are not serialized i.e. their values are not present in the stream. So when you read an object back from the stream, those values will not come from that stream. There can be other ways though which the static fields may get initialized. For example, they can be initialized as a part of class initialization or they can get their default values as a part of class loading.
Question 2

When you said "static fields are never serialized," did you mean ignoring all static fields in the process of serialization whether or not the static variables contain programmer-initialized values or the default values assigned to them by the compiler?

I'm simply trying to understand this concept. I have no other intention.

Thanks.

Schmichael
Values of static fields will not be present in the stream. Period. it doesn't matter who assigned that value or how that value got assigned to the field.
If you like our products and services, please help us by posting your review here.

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

Remember that static fields are never serialized irrespective of whether they are marked transient or not. In fact, making static fields as transient is redundant. Thus, f1, f2 and f4 will not be serialized at all. However, since f4 is being initialized as a part of class initialization, it will be initialized to the same value in another JVM. Thus, its value will be same as the one initialized by the code.
The above quote is from the explanation underneath your answer options and the following is the correct answer option.

f4, f5

What's being asked in the problem was
Which fields of the above class will be preserved when the object referred to by the variable 'd' is serialized and deserialized in another JVM?
To preserve something, you have to serialize it so that you can see/reuse what's preserved after it being deserialized.

Is that correct?

In your explanation, you said "Thus, f1, f2 and f4 will not be serialized at all."

If f2 is not serialized, that means it's not preserved.

How did f2 then end up being in the correct answer choice above that is asking for something that's preserved?

As you said in your previous answer that "Static variables are not serialized. Period." Therefore f1 and f4 did not get serialized as you put it in your explanation above.

What made f2 an exception so that it can be preserved and ended up in the correct answer choice?

There must be something I'm missing here.

Thanks a lot for your time and explanation.

Schmichael

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by admin »

1. Please mention the questionid so that we can be sure about what question your are talking about. I believe you are talking about 2.1620.
2. The question is asking you about the code that is given. It explicitly asks you about the values of the variable/fields of the object referred to by variable d after it makes changes to some of the fields, serializes it, and then deserializes it back. It is not asking a general question about about whether values of static variables are preserved or not (they are not, as discussed above).
3. Here, f4 is static and final and it is being initialized as a part of class loading. This value is not being changed. Therefore, you will see the same value after deserialization. That this value is same as before has nothing to do with serialization. It is preserved nonetheless (due to other mechanism) and therefore part of the correct answer.
4. Values of f1 and f2 will not be the same as the ones you had before serialization and are, therefore, not correct.
5. The explanation that you've quoted says the same thing:
Thus, f1, f2 and f4 will not be serialized at all. However, since f4 is being initialized as a part of class initialization, it will be initialized to the same value in another JVM. Thus, its value will be same as the one initialized by the code.
In the real exam also, you should not expect that the question is testing you on just one concept. It may have you thinking about one rule but the answer could very well depend you knowing and applying a few other rules as well.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

Code: Select all

Given the following code:  public class Data implements java.io.Serializable{         public static String f1;         public static transient int f2;         public transient boolean f3;         public final static String f4 = "4";         public String f5 = "5"; }  Data d = new Data(); d.f1 = "f1"; d.f2 = "f2"; d.f3 = true;   Which fields of the above class will be preserved when the object referred to by the variable 'd' is serialized and deserialized in another JVM?
This is the question and its ID: enthuware.ocpjp.v8.2.1620.

Paul,

This is the concept I would say I'm so lost on. I've spent hours and hours and still don't get this concept down. The more I read on this concept, the more I get lost and confused. My further reading is not helping me at this moment. I mentioned the link of the book I've been reading.

Serialization, according to the book, seems to allude to writing to the disk. That's right! The word "disk" is used in the text book when discussing serialization and deserialization.

I seem to getting all mixed messages and wrong information along the way while trying to understand the concept and I'm hopelessly lost right now.

As you may be aware in the past, one or the most two answers from one of you was enough for me to get a concept.

Schmichael

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

f3, f5
Members marked transient are not serialized. Therefore, f3 will not be preserved.
This is the wrong answer choice, i.e. the answer not to be picked, but if you look at its explanation highlighted in bold above, I think it's fair to conclude that no serialization means no preservation.
Remember that static fields are never serialized irrespective of whether they are marked transient or not. In fact, making static fields as transient is redundant. Thus, f1, f2 and f4 will not be serialized at all. However, since f4 is being initialized as a part of class initialization, it will be initialized to the same value in another JVM. Thus, its value will be same as the one initialized by the code.
f4 is not serialized and therefore, it cannot be preserved. If it can't be preserved, how did it end up in the correct answer choice that calls for the preserved values?

You said
It is preserved nonetheless (due to other mechanism) and therefore part of the correct answer.
in the answer you wrote back to me here earlier.

Would you like to explain what that other mechanism is?

Without it, I felt like I would have to learn this concept on the basis of "Paul told me so." rather than getting the stuff.

Thanks a lot, Paul. Don't mean to be pesky.

Schmichael

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by admin »

schchen2000 wrote:
f3, f5
Members marked transient are not serialized. Therefore, f3 will not be preserved.
This is the wrong answer choice, i.e. the answer not to be picked, but if you look at its explanation highlighted in bold above, I think it's fair to conclude that no serialization means no preservation.
No, it is incorrect to conclude that no serialization means no preservation as a general rule. In this particular case, f3 is an instance variable. Since its value is not same as its default value, serialization is the only means through which it can be preserved. But it is declared transient, which excludes it from being serialized.

But I agree that this explanation can be a source for this kind of deliberate misinterpretation. If you take this plus the explanation at the bottom of the question, I think it is quite clear what the question is getting at and why the correct option is correct. An argument can still be made that this sentence, in isolation, can be interpreted in the manner you have described and to avoid that we will improve it.
Remember that static fields are never serialized irrespective of whether they are marked transient or not. In fact, making static fields as transient is redundant. Thus, f1, f2 and f4 will not be serialized at all. However, since f4 is being initialized as a part of class initialization, it will be initialized to the same value in another JVM. Thus, its value will be same as the one initialized by the code.
f4 is not serialized and therefore, it cannot be preserved. If it can't be preserved, how did it end up in the correct answer choice that calls for the preserved values?

You said
It is preserved nonetheless (due to other mechanism) and therefore part of the correct answer.
in the answer you wrote back to me here earlier.

Would you like to explain what that other mechanism is?
In this case that other mechanism is class initialization. The field is initialized to the same value as it had before it was serialized.
If you like our products and services, please help us by posting your review here.

schchen2000
Posts: 106
Joined: Mon Mar 28, 2016 11:36 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by schchen2000 »

this kind of deliberate misinterpretation
Thanks for your previous answer. Deliberate misinterpretation wasn't my intention. I clearly struggled with this concept as I've said in one of my previous comments.

As I was so lost, I was looking at everything that's given as part of the answer to this question in order to make sense out of all this on my own.

I did not mean to present you a deliberate misinterpretation and I'm not writing this defensively.

Once again, thank you very much for your time and answers.

I have greatly benefited from your question bank and thoughtful answers on this forum.

Thank you.

Schmichael

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Why Static variables not included in a serialization pro

Post by admin »

ok, cool. No problem 8-)
-Paul.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 69 guests