Java – the best string technology equals comparison
•
Java
If the block is better?
private static void checkStr(String str) { if (str.equals("exit")) { System.out.println("It is equal"); } if ("exit".equals(str)) { System.out.println("It is equal"); } }
Solution
Using the first method, you can provide margin for nullpointerexceptions So from my point of view, the second one is better
In the case of constants, you should prefer the second method to the first
"exit".equals(str)
You can find a detailed explanation here
I personally prefer another method Apache Commons – commons Lang has objectutils equals(Object,Object). Using this method, it is always safe even if null values are used
From documentation:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码