1

I notice some people seem to differ when comparing two strings together, such as when comparing a variable to a constant. For example, let's say we have a constant string and an input method:

public final String CONSTANT_STRING = "A constant string";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Is it better or faster in any way to use the unknown input first:

br.readLine().equals(CONSTANT_STRING)

or to compare the constant to the unknown:

CONSTANT_STRING.equals(br.readLine());
1
  • 1
    Using the second option is called a Yoda condition.
    – Eric
    Commented Nov 2, 2023 at 16:49

4 Answers 4

10

Its not a matter of performance. The second version won't ever produce a NullPointerException, even when br.readLine() returns null. The first one does though.

3

It's not better or faster, but if you know that CONSTANT_STRING exists you guarantee that you'll never get a NullPointerException if you do it the second way.

2

equals() method of String class will return false if the length of two comparing strings are different. It will compare the contents only when the length of two strings are equal. So the order does not affect the performance.

As you can see in other answers, second method will not occur NullPointerException. So, the second method is better.

1

public abstract? String CONSTANT_STRING = "A constant string";

1
  • whoops, I'll fix that quick.
    – ldam
    Commented Jan 4, 2013 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.