Wednesday, November 18, 2009

Core Java interview questions with Code Example

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?

Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:


import java.io.*;

public class HelloWorld {
public static void main(String[] args) {
try {
PrintStream st = new PrintStream(new FileOutputStream("test.txt"));
System.setOut(st);
System.setErr(st);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}


Question: Explain the usage of the keyword transient?

Answer: Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. Sometimes serialization is necessary. For example, when we transmit objects through network, we want them to be consistent, therefore these objects have to be sterilizable,

On the other hand, we don't want the value of some member variable to be sterilizable, for instance, the password, then we use the keyword transient. When the class will be de-serialized, the transient variable will be initialized to 0 or null.


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

public class Logon implements Serializable {
private transient String password;

public Logon(String pwd) {
password = pwd;
}

public String toString() {
return password;
}

public static void main(String[] args) throws Exception {
Logon a = new Logon("hello_world");
System.out.println("logon a = " + a);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"Logon.out"));
o.writeObject(a);
o.close();
Thread.sleep(1000); // Delay for 1 second
// Now get them back:
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"Logon.out"));
System.out.println("Recovering object at after 1 second");
a = (Logon) in.readObject();
System.out.println("logon a = " + a);
}
}


The output of the above example will be:

logon a = hello_world
Recovering object at after 1 second
logon a = null

1 comment:

  1. Great post folks! I am new to JAVA programming and these type of questions are really really helpful for me. I will definitely bookmark your blog for future references. thanks again.

    ReplyDelete

meta.ai impression

Meta.ai is released by meta yesterday, it is super fast you can generate image while typing! You can ask meta.ai to draw a cat with curvy fu...