Java | Class and Object | Question 2

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 = new Test(); 
      System.out.println(t.i);
   
}

chevron_right


(A) garbage value
(B) 0
(C) compiler error
(D) runtime error


Answer: (B)

Explanation: In Java, fields of classes and objects that do not have an explicit initializer and elements of arrays are automatically initialized with the default value for their type (false for boolean, 0 for all numerical types, null for all reference types). Local variables in Java must be definitely assigned to before they are accessed, or it is a compile error.


Quiz of this Question



My Personal Notes arrow_drop_up