Calling equals on string literal

后端 未结 8 1271
再見小時候
再見小時候 2020-12-29 04:32

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

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


        
8条回答
  •  执笔经年
    2020-12-29 05:25

    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.

提交回复
热议问题