1

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?

13
  • 7
    That completely depends on the context of the code. Sometimes you'd rather have a NPE rather than doing a mistaken operation on an empty string and thinking everything is ok. Ideally though, you don't have either, but that will require you to write the code appropriately.
    – user40980
    Commented Jul 27, 2015 at 16:07
  • 1
    Just to add to the confusion: null is widely considered a billion-dollar mistake. It was created because it's so easy to implement, but it introduces an unnecessary special case into program logic that causes endless troubles. If at all possible, try to program as if null didn't exist and avoid all this trouble. This means paying the price for an occasional "" here and there, but nowadays this is a good trade-off even in the small environment of mobile devices. Commented Jul 27, 2015 at 16:11
  • 1
    @RajatSaxena Are null references really a bad thing?
    – user40980
    Commented Jul 27, 2015 at 16:14
  • 1
    @Panzercrisis Correct - I don't completely agree with it. However, if one lacks the discipline and instead writes sloppy code NPE pop up everywhere (and thus the billion dollar mistake). If one is going to be undisciplined with assignments and tests, then the NullObject pattern is probably safer to use.
    – user40980
    Commented Jul 27, 2015 at 16:22
  • 2
    The object allocated by new String() would be garbage collected as there are likely no other references to it. Why one does this as a two statements, I don't know. Why not String a = "Harry"; in the first place? Or leave it unassigned until you actually use it?
    – user40980
    Commented Jul 27, 2015 at 16:25

3 Answers 3

11

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.

1
  • 2
    Agreed. But also, if the OP doesn't need to change s, they should initialize it once and make it final. No need to mess with null or empty Strings :)
    – Andres F.
    Commented Aug 6, 2015 at 2:51
8

In general you want to keep declaration and initialisation as close as possible to minimise exactly the type of problem you're talking about.

There is also the issue of redundant initialisation where the value null you're assigning is never used which is extra code that harms readability even if the redundant assignment is optimised away by the compiler.

Sometimes assigning some sort of default value is unavoidable, for example if you declare before a try catch, initialise inside and use it afterwards. For other types you can often find a more natural default value such as an empty list.

1
  • 1
    It is avoidable, just rethrow in catch blocks, and compiler would understand that there are no branches leaving variable uninitialized after the block.
    – Basilevs
    Commented Dec 16, 2016 at 2:44
0

There are two different views of "initialisation". One is that a variable has a defined value after initialisation. One is that a variable has a useful value. Neither setting this variable to null or to new String () will set it to a useful value.

Using the variable is a bug, whether it is uninitalised or just not set to something useful. The compiler is very good at finding situations where a variable is used while uninitialised (and doesn't allow it). But by setting the variable to null or new String (), you remove the compiler's ability to tell you when there is no useful value. For example:

String a = null;
if (condition1) a = "Yes";
else if (condition2) a = "No";

If neither condition is true, a isn't set to anything useful, but the compiler can't tell you about it anymore. So we have a bug, but you destroyed the compilers ability to report it. If you hadn't initialised a, the compiler would tell you.

Not the answer you're looking for? Browse other questions tagged or ask your own question.