Java | Class and Object | Question 1

Predict the output of following Java program?

filter_none

edit
close

play_arrow

link
brightness_4
code

class Test {
  int i;
class Main {
   public static void main(String args[]) { 
     Test t; 
     System.out.println(t.i); 
}  

chevron_right


(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.

filter_none

edit
close

play_arrow

link
brightness_4
code

class Test {
  int i;
class Main {
   public static void main(String args[]) { 
     Test t = new Test(); 
     System.out.println(t.i); 
}  

chevron_right



Quiz of this Question



My Personal Notes arrow_drop_up