Open In App

Java | Class and Object | Question 1

Like Article
Like
Save
Share
Report

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


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads