The left and right variable positions of the equals() method in Java
A variable and a constant, use the equals() method to compare, whether it is better to put the constant first or the variable first
If both are variables, then where to put them It doesn’t make any difference;
Now the main thing is that there is a constant, the equals() method is defined in the Object class, that is to say, any object can call the equals() method, but when the object calls the method, if If the object is null, the system will report a null pointer exception when running; if an exception occurs, this is obviously something we don't want to see;
If you put the variable in front, it is equivalent to calling the equals method of this variable, then if this variable is empty NullPointException will be reported when , so it is definitely better to put the constant in front; in this way, there is no need to handle the null pointer exception.
Let’s talk about one more thing, why does the null pointer exception not occur when the variable is placed in parentheses? Haha, actually think about it, can the equals() method compare whether a variable is equal to null, that is,
s.equals(null);
You can just write null directly in the brackets, are you still afraid that the variable is null?
For more articles related to the left and right variable positions of the equals() method in Java, please pay attention to the PHP Chinese website!