Why in Java, (“string”).equals(var) recommended other than (var).equals(“string”)?

前端 未结 5 764
盖世英雄少女心
盖世英雄少女心 2021-01-06 04:15

I have seen most cases developers use first string and after that variable used in .equal operation. What is the reason?

相关标签:
5条回答
  • 2021-01-06 05:03

    why in Java, (“string”).equals(var) recommended other than (var).equals(“string”)?

    This is because you do not know for sure what is var pointing to. It may very well be null because of which you may get NPE which will kill your current Thread. So 2nd approach is preferred as (“string”).equals(var) returns false.

    For example consider you getting this var in your servlet

    String var = request.getParameter("myvar");
    if(var.equals("myVarValue")) {
    //do something
    }
    

    This will throw NPE if parameter is not coming in your request.

    0 讨论(0)
  • 2021-01-06 05:03

    I would not use ("string").equals(var), since it may show that the programmer does not know if var might be null or not. I would document if a var can be null or not and check it.

    Example:

    String makeAString(@NonNull String aStringValue) {
        Validate.notNull(aStringValue, "aStringValue must not be null");
        if (aStringValue.equals("abcde") {
           return "fg";
       } else {
           return "de";
       }
    }
    
    String makeAString(@Nullable String aStringValue) {
        if (aStringValue == null) {
           return "kl";
        }
        if (aStringValue.equals("abcde") {
           return "fg";
        } else {
           return "de";
        }
    }
    
    0 讨论(0)
  • 2021-01-06 05:05

    Because if var is null you won't raise a NullPointerException.

    0 讨论(0)
  • 2021-01-06 05:05
    public static void badOne() {
        String s = null;
        System.out.println(s.equals("abc"));
        // This function will throw null pointer
    }
    
    public static void goodOne() {
        String s = null;
        System.out.println("abc".equals(s));
        // This will print false
    }
    
    0 讨论(0)
  • 2021-01-06 05:06

    Because var can be null and var.equals("string") will throw NullPointerException (attempt to call of method on null). On the other hand, "string".equals(null) will just return false.

    0 讨论(0)
提交回复
热议问题