Java – Difference Between String a = null and String a = new String()

java

It's a pretty naive question to ask but I got this doubt while programming for Android. I use to initialize my new strings like String a=null, so in my code there remains a probability to get NullPointerException if I forget to initialize the variable before accessing it but what about the other case. Also which one should be used?

Best Answer

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

That being clear, I would recommend you to use a "smart default". 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 produce an exception because it indicates something wrong happened under the hood that should not have happened.

Related Topic