What is the result?

Given:

import java.io.*;
public class Forest implements Serializable {
private Tree tree = new Tree();
public static void main(String [] args) {
Forest f = new Forest();
try {

FileOutputStream fs = new FileOutputStream(“Forest.ser”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(f); os.close();
} catch (Exception ex) { ex.printStackTrace(); }
}
}

class Tree { }

What is the result?

Given:

import java.io.*;
public class Forest implements Serializable {
private Tree tree = new Tree();
public static void main(String [] args) {
Forest f = new Forest();
try {

FileOutputStream fs = new FileOutputStream(“Forest.ser”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(f); os.close();
} catch (Exception ex) { ex.printStackTrace(); }
}
}

class Tree { }

What is the result?

A.
Compilation fails.

B.
An exception is thrown at runtime.

C.
An instance of Forest is serialized.

D.
An instance of Forest and an instance of Tree are both serialized.

Explanation:
java.io.FileNotFoundException: Forest.ser (Permission denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
at Forest.main(Main.java:8)



Leave a Reply 2

Your email address will not be published. Required fields are marked *


Anon

Anon

java.io.NotSerializableException: practice.Tree
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
at practice.Forest.main(Forest.java:19)

fjbo221

fjbo221

For answer D., use
class Tree implements Serializable { }