Question

After chasing down some NullPointerExceptions in a a recent project I finally found where they came from and it surprised me. Although I can now accurately describe where they came from and how to prevent them, I am still confused about how this kind of behavior can be allowed to happen without warning from the compiler or at least the IDE.

I had a browse around Stack and did some fairly extensive googling but can't find anything written about this. To cut to the chase here is some code demonstrating this odd behavior;

public class Test {

        String what, why, where = "who knows?";

        public static void main(String[] args) {         
           System.out.println("The 'what' String = " +new Test().what);
        }
    }

Output;

The 'what' String = null

This shows the correct output if you declare and instantiate each String separately, but chaining them together like this causes them to be instantiated null. So, the question is why? And if this is standard behavior, then why does the compiler even allow us to instantiate String objects this way?

Was it helpful?

Solution

Because internally it goes down to :

String what=null;
String why = null;
String where="who knows?"; // declaring 2 strings, only assigning the value to the third one.

OTHER TIPS

String what, why, where = "who knows?"; sets value only for the where variable, while the others are set to their default one, which is null (if they are class members, of course).

You can do the following: (assuming you want all of them to have the same value):

String what, why, where;
what = why = where = "who knows?"

Note that these two statements should be within a method, constructor or (static) initializer.

That's equalant to following, only where get initialized to the given value "who knows?", other set to default value null

String what;
String why;
String where="who knows?";

Try

String what, why, where;
what = why = where = "who knows?";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top