Hi
In the question below the answer is 3.But i was under the notion that transient variables cannot be serialized.then how come the answer is 3.please do explain.thanks
Archana
import java.io.*;
public class TransientWriter implements Externalizable
{
private transient String s = "Hope I can ever be persistant!";
public void writeExternal(ObjectOutput oOut) throws IOException
{
oOut.writeObject(s);
}
public void readExternal(ObjectInput oIn) throws IOException, ClassNotFoundException
{
s=(String)oIn.readObject();
}
public String toString()
{
return s;
}
}
class K
{
public static void main(String args[]) throws IOException, ClassNotFoundException
{
TransientWriter tw = new TransientWriter();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tw.out"));
out.writeObject(tw);
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tw.out"));
TransientWriter tw2 = (TransientWriter) in.readObject();
System.out.println(tw2);
}
}
Attempting to compile and run the above code
1)will cause a compiler error due to the attempt to write a transient object.
2)will cause a runtime exception when an attempt is made to write a transient object.
3)will not cause any runtime error and the transient object is writen to the file named "tw.out".
4)will not cause any runtime error and the transient object is not written to the file named "tw.out". The program prints a blank line on the screen.