Search code examples
javanulldefault

How to print the default value of an object?


If t1 gives compile error, t2 prints memory address, t3 prints null, then what would you write to get the default value of an object (null) printed.

public class Test {

public Test{

}
public static void main(String[] args) {
    Test t1;                              
    Test t2= new Test();                  
    Test t3= null;                        
    System.out.println(t1);            //compile error uninitialized
    System.out.println(t2);            //prints memory address
    System.out.println(t3);            //prints null

}
}

Solution

  • Only instance or static variables (declared at class scope) have a default value. Local variable (declared at method scope) do not have default values: you are required to initialize these variables before you use them.

    So the compiler is correct when it rejects the printing of t1 (with a compile error): you haven't assigned a value to this variable at that point in the method, and it's a local variable, so it does not have a default value.