I have seen most cases developers use first string and after that variable used in .equal
operation. What is the reason?
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.