which if 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");
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
With the first approach you are giving margin to
NullPointerExceptions. So from my point of view the second one is better.For the case of constants you should prefer always the second approach over the first one.
You can find a detailed explanation here
I personally prefer another approach. Apache Commons – commons lang have
ObjectUtils.equals(Object, Object). With this approach you are always safe even with null values.From documentation: