RAQ: Rarely asked questions
---------------------------
I guess these questions are not really very difficult so you should be
able to
answer them just by reading them or try it yourself. I have prepared
these from
various sources(none of this is mine) so if the question seem your
original
then I thank you for the contribution duely respecting copyrights.
Here, I have not tried to explain each answer elaborately as I prepared
this
on the fly along the way I work and code. Please see me as just one of
you
while reading questions and answers and forgive me if I sound terrible
before
you suggest correction to what you see as errornous.
Please let me know if you hate/love these questions and can't resist to
have
a chat with me.
Also feel free to
on scale of 1 to 10 with 10 being highest(excellent) and 1 being lowest(poor).
Please write rating in the subject line itself after 'Rating=', which will make my filtering easier :).
You can comment further in the email message.
The reason I name these as RAQ is- they are not FAQ.
__________________________________________________________________
Email: [email protected]
__________________________________________________________________
1. What happens when we try to compile the following code?
class GoogleMagic {
public static void main(String[] s) {
System.out.println("Here starts
the magic...");
http://WWW.Google.COM;
System.out.println("Here ends the
magic.");
}
}
Ans:
----
"http:" here is considered to be a label and rest of the line is
ignored as
comment!
2. What would be the output of the following program in following
scenarios,
a) <<replace>> = private
b) <<replace>> = public
Explain reason for each output about "what happens".
class A {
<<replace>> void m1() {
System.out.println("A.m1");
}
public void m2() {
m1();
System.out.println("A.m2");
}
}
class B extends A {
public void m1() {
System.out.println("B.m1");
}
public void m2() {
System.out.println("B.m2");
}
}
class test {
public static void main(String[] s) {
B b = new B();
b.m2();
}
}
3. Explain what happens when we try to compile the following.
What would be the output if we are able to compile the
code?
class test {
public void trimIt(String s) {
s.trim();
}
public static void main(String[] s) {
test t = new test();
String String = " Trim
Me ";
t.trimIt(String);
System.out.println(String);
}
}
4. Write the output of the following code.
class test {
public static void main(String[] s) {
System.out.println("Start");
for(int i=0; i < 10; i = i++ )
{
System.out.println("Processing...");
}
System.out.println("End");
}
}
5. Consider the following code.
class A {
public void m1(int i) {
System.out.println("A.m1:"+i);
}
}
class B extends A {
public void m1(long i) {
System.out.println("B.m1:"+i);
}
}
class test {
public static void
main(String[] s) {
B b = new B();
b.m1(999999); // Line-1
A a = new B();
a.m1(999999); // Line-2
}
}
5.1 What would be the result of the compilation of the above code?
5.2 What would be the result of the compilation of the above code when
Statement at "Line-1" is commented fully?
Explain results in each scenario.
6. Explain the output of the program upon compiling and if it is able
to get
compiled then what would be the output at runtime?
import java.util.Vector;
class Person {
private String name;
private String ssn;
Person() {
}
Person(String name,String ssn) {
this.name = name;
this.ssn = ssn;
}
public void setName(String name) { this.name = name;
}
public void setSSN(String ssn) { this.ssn = ssn; }
public String toString() {
return name+":"+ssn;
}
}
class vectorTest {
public static void main(String[] s) {
Vector roster = new Vector();
Person tempPerson = new Person();
for(int i=0; i < 5; i++) {
tempPerson.setName("Person"+i);
tempPerson.setSSN(i+"");
roster.add(tempPerson);
}
http://www.Yahoo.com;
for(int j=0; j < 5 ; j++) {
System.out.println(((Person)roster.elementAt(j)).toString());
}
}
}
Ans:
----
http://www.Yahoo.com line will be interpreted as,
http: = label
// = comment
7. What will be the output of the following? Will you complete your
Masters Degree? :)
class test {
public static void main(String[] s) {
byte b = 0;
System.out.println("Good Luck.
You are starting Masters Degree at USC");
while( ++b > 0 );
System.out.println("Congrats!!!
You got graduated from School!");
}
}
Good Luck. You are starting Masters Degree at USC
Congrats!!! You got graduated from School!
8. Declare a constant array of constant int in Java.
Can't do it.
9. Explain System.out.println().
Ans:
----
println() is a instance method in PrintStream class
out is static reference in System class of type PrintStream
When we say System.out.println() it is accessing static out
member of System class and then calling instance method on that
reference.
10. Write the output of the following program.
abstract class base {
abstract void getName(base
b);
}
class test2 extends base {
void main() {
getName(this);
}
void getName(base b) {
System.out.println(b.getClass().getName()); }
static void main(String[] s)
{
test2 t2 = new test2();
t2.main();
}
}
Ans:
----
test2
11. What would happen when we run the following program?
class test {
public static void method1() {
System.out.println("Hi! I am
test.method1");
}
public static void main(String[] s) {
test t = new test();
t = null;
t.method1();
}
}
Ans:
----
Hi! I am test.method1
As method1 is static it doesn't raise NullPointerException.
12. What will be the output of the following code when run?
import java.util.*;
class test4 {
public static void
main(String[] s) {
String temp = "1, 2, 3 , 4, 5, 6, 7, 8";
StringTokenizer stk = new StringTokenizer(temp,",");
while (stk.hasMoreTokens() ) {
stk.hasMoreTokens();
System.out.println(stk.nextToken().trim());
}
}
}
Ans:
----
1
2
3
4
5
6
7
8
hasMoreTokens() is atomic. It doesn't increase the pointer. Only
nextToken() does that.
13. Write the output of the following.
class test {
static void main(String[] s) {
StringBuffer sb1 = new
StringBuffer("Java");
StringBuffer sb2 = new
StringBuffer("Java");
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
}
}
Ans:
----
false
false
As sb1 == sb2 equates references which are different and equals() method
is not overridden in StringBuffer by which it could return true for the
second SOP.
14. What will be the output of following given the below folder
hierarchy?
(this is on Unix platform)
maulin (folder)
|___dir1 (folder)
|___temp.txt (file)
|___test.java (file)
test.java:
import java.io.*;
class test {
public static void main(String[] args) throws
Exception {
System.out.println(System.getProperty("user.dir"));
File f = new File("temp.txt");
System.out.println(f.getCanonicalPath());
System.out.println(System.setProperty("user.dir","/maulin/dir1"));
File f1 = new File("temp.txt");
System.out.println(f1.getCanonicalPath());
System.out.println(System.getProperty("user.dir"));
}
}
15.
A) What does the following code do?
B) What will be the output of the following program?
C) What is the flow in the code that can cause
misbehavior when we add Entry objects into the
TreeMap structure?
import java.util.*;
class Entry implements Comparable {
String name;
int value;
public Entry(String name, int value ) {
this.name = name;
this.value = value;
}
public int compareTo(Object o) {
return this.value -
((Entry)o).value;
}
public String toString() {
return "{ " +name+" , "+value+"
}";
}
}
public class testTreeMap {
public static void main(String[] args) {
TreeMap tm = new TreeMap();
String[] names = new
String[]{"zebra","maulin","soham"};
int[] values = new int[]{0,2,2};
for(int i=0; i < names.length;
i++) {
System.out.println(tm.put(new Entry(names[i],values[i]),new
Integer(values[i])));
}
Set ks = tm.keySet();
Iterator iter = ks.iterator();
while ( iter.hasNext() ) {
System.out.println(iter.next());
}
}
}
ANS:
----
A) It sorts the Entry objects based on 'value'
B) null
null
2
{ zebra, 0 }
{ maulin, 2 }
C) Flaw is that compareTo() is not compatible with equals() which causes
only first two Entry objects go in the TreeMap instead all
of three.
16. What is the difference between API and Implementation?
e.g. JAXP and Xerces-J. Do we need to have both or only one?
ANS:
----
JAXP is the API, Xerces-J is the Implementation of JAXP. We need both.
17. What will be the output of the following program? Explain your
answer.
class TestParent {
int a=100;
static {
System.out.println("TestParent.static init");
}
TestParent() {
System.out.println("TestParent.constructor: a="+a);
incr();
}
void incr() {
a++;
System.out.println("TestParent.incr: a="+a);
}
int getVar() { return a; }
}
class TestChild extends TestParent {
int a=-10;
static {
System.out.println("TestChild.static init");
}
TestChild() {
System.out.println("TestChild.constructor: a="+a);
incr();
}
void incr() {
a+=10;
System.out.println("TestChild.incr: a="+a);
}
int getVar() { return a; }
}
public class TestInheritance1 {
public static void main(String[] args) {
TestChild tc = new TestChild();
System.out.println("Result:"+tc.getVar());
}
}
ANS:
----
TestParent.static init
TestChild.static init
TestParent.constructor: a=100
TestChild.incr: a=10
TestChild.constructor: a=-10
TestChild.incr: a=0
Result:0
Explanation:
The sequence of initialization of any class,
1. static vars
2. static blocks
3. parent class (if extends relationship)
4. instance vars
5. rest of the constructor code
18. What is a "Magic Word" in computer arena? Do we have one for Java?
What is that "magic word" for Java?
ANS:
----
magic word is a special code so that OS can identify the file types
based on the file content. for java it is "CAFEBABE".
19. What is "green thread"? If we say some code won't work on "green
thread"
based JVMs what does that mean?
ANS:
----
Green Thread is a thread that doesn't get mapped to the OS level
thread. Its
an application level thread.
When somebody says that some code won't work on 'green thread' based
JVMs
it means that the code is not taking care of calling yeild() at
appropriate
times and as JVM is executing the threads at application level it can
hog
the application for indefinite amount of time.
20. What is the output of following program if we try to compile it and
run it?
public class Test
{
public Test(Object obj)
{
System.out.println("Constructor A.");
}
public Test(String s)
{
System.out.println("Constructor B.");
}
public static void main(String args[])
{
new Test(null);
}
}
ANS:
----
Constructor B.
Because String is a subclass of Object and so it is more specific class
that matches null before Object.
21. If you have a shell script then write a code in Java to invoke it
and run it in the background. e.g. if the shell script name is ,
shscript then your code should achieve the same effect as,
"$shscript &" command.
ANS:
----
Hint: you can't put a process in background directly from java using
Runtime.exec()...
22. Consider the below code,
public class arrayTest1 {
public static void main(String[] args) {
// line:arr1
int[][][][][] a = new
int[3][4][5][10][98];
//line:arr2
//int[][][][][] a = new
int[3][4][5][10][];
// line:1
a[2][0][0][0] = new int[100];
// line:2
a[3][0][0][0] = new int[100];
// line:3
a[0][0][0][0] = new int[1000];
a[0][0][0][0][98] = 10;
System.out.println("Done");
}
}
what happens when,
1. we comment line below "line:2". Explain the reason.
2. we comment line below "line:3". Explain the reason.
3. what happens when we comment line below "line:arr1" and
uncomment line below "line:arr2" and comment line below
"line:3" simulataneously?
ANS:
----
HINT: the last dimension index doesn't matter so we can
say what we do in line:3 but if we remove it then the below
statement is not applicable as the original size was 98.
when we don't sepcify the last index limit (like line:arr2)
then the default array ref is NULL so the 2nd line after
"line:3" gives NPE if we remove line below "line:3"
23. What does the following code do on Windows?
mport java.io.*;
public class dir {
public static void
main(String[] s) throws Exception {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("dir");
p.waitFor();
BufferedReader br = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line = "";
line = br.readLine();
while ( line != null ) {
System.out.println(line);
line = br.readLine();
}
br.close();
}
}
ANS:
----
Doesn't work and throws IOException, error=2 as "dir" is "internal dos"
command and can't be
executed by windows directly hence JRE also can't execute it.
(NOTE: Similar program with "ls" command on Unix will work).
24. Write a method to swap two strings in Java.
25. What happens when we run the following code.
class myThread extends Thread {
public void run() {
System.out.println("In
myThread.run()");
}
}
class myRunnable implements Runnable {
public void run() {
System.out.println("In
myRunnable.run()");
}
}
public class test {
public static void main(String[] args) {
myThread mth = new myThread(new
myRunnable());
mth.start();
}
}
26.
a) What is meant by "immutable"/"mutable" objects?
b) If we provide only "Getter" methods in our code for the data members
then does
that mean our class is immutable? (Provided we don't have any other
methods manipulating
the data members).
c) Where do we need the "mutability"?
ANS:
----
b)
No. Because if we have mutable attributes in the code then it is a
problem.
e.g. if we have a method,
private Point p;
public Point getPoint() {
return p;
}
main()...
Point p = getPoint();
p.setX(300); // we are messed up!!
c)
awt/swing can't add one component at two places. we have to do clone()
them
to "drag and drop".
27.
a) How would you clone an object?
b) Can you use something like "copy constructor" for clonning? Explain
answer.
c) What could be some other ways for clonning instead using Clonnable
interface?
d) Modify the below code to have a clonning capability,
class list {
list l;
int i;
list(int i) {
this.i = i;
if ( --i > 0 )
l = new list();
}
void incr() {
i++;
if ( l != null )
l.incr();
}
}
28. If we have 256 MB RAM then what is the maximum length of double
array we
can create? (Ignore the jvm memory occupied and everything else)
Ans:
----
Integer.MAX_VALUE as the length() method must return correct
'int' length.
29. What does this return?
Integer.parseInt("Jack",27);
Ans:
----
381611
30. In a servlet/jsp which is the "current dir" when you run a code
from the
servlet/jsp that refers to the "current dir" something like,
File f = new File("test.txt");
Ans:
----
The one from where the webserver was started actually.
e.g. on iPlanet it would be- config directory.
on Tomcat it would be /bin directory
31. What is serialVersionUID and what problems we might face w.r.t to
this?
32. Express your views about when to use Singleton and a class with all
static
methods?
33. If we have a class e.g. Employee, object of which, we want to pass
between
client and server (written based on sockets) written in java with the
following constraint,
- we don't want Employee.class file on theee client side
The reason being, if we change Employee.java file (hence Employee.class
file)
then it becomes difficult to make client have the latest .class file
always.
How we will go about it?
You can add/remove/rename objects/files here.