Predict the output of following Java program?
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t;
System.out.println(t.i);
}
|
(A) 0
(B) garbage value
(C) compiler error
(D) runtime error
Answer: (C)
Explanation: t is just a reference, the object referred by t is not allocated any memory. Unlike C++, in Java all non-primitive objects must be explicitly allocated and these objects are allocated on heap. The following is corrected program.
class Test {
int i;
}
class Main {
public static void main(String args[]) {
Test t = new Test();
System.out.println(t.i);
}
|
Quiz of this Question