Skip to content
Advertisement

Calling equals on string literal

I just was tidying my code a bit and there was this piece:

String saving = getValue();
if(saving != null && saving.equals("true")){
   // do something
}

Then I thought of doing it the other way around to get rid of the checking for null:

if("true".equals(saving)){
   // do something
}

It definitely works, but is this safe to do so? I mean string literals are stored in a common pool, while string object create by new are on the heap. But strings in the constant pool are also objects, right?

But still it doesn’t seem like the right thing to do, even though it makes the code shorter.

Advertisement

Answer

This is safe – and as you have seen, a good way of avoiding null pointers.

You mention the use of new for Strings. Many java static code analysis tools will recommend always using literals over new String("foo");.

Edit:

If you wanted, you could even just use:

if (Boolean.valueOf(saving)) {
    ...
}

According to the docs, passing null will return false.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement