Skip to main content
1 of 4
Tulains Córdova
  • 39.5k
  • 13
  • 99
  • 155

First let's clarify something: You mention that after assigning null to the variable you could forget to initialize it, but by assigning null to it you are in effect initializing it.

public static void main (String args[]){
    String s;       
    System.out.println(s); // compiler error variable may not be initialized
}

vs

public static void main (String args[]){
    String s=null;      
    System.out.println(s); // no compiler error
    System.out.println(s.equals("helo")); // but this will generate an exception
}

So after you do String s=null; there's is no way that you could forget to initialize because you did initialize.

That being clear, I would recommend you to use a "smart defaults". In your case perhaps the empty string "" would be a good default value if you want to avoid NullPointerException. In the other hand, sometimes it is desirable that the program to produce an exception because it indicates something wrong happened under the hoods that should not have happened.

Tulains Córdova
  • 39.5k
  • 13
  • 99
  • 155