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

前端 未结 5 795
盖世英雄少女心
盖世英雄少女心 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.

提交回复
热议问题