Java: String Equality (Common Mistake)
A very common mistake that lots of Java programmers will make is to use "==" to compare strings, rather than ".equals". That's what I keep reminding myself all the time and I never use "==" to do any string compare.
Just today, when I was testing a Java program, I noticed that the programmer used "==" to compare strings, everywhere in the 4000-line program. Why there's no logic error in the program? Why is the program still getting the correct output?
My first guess, in certain case, Java will return the correct result. But, when will Java give you correct result if you use "==" to do string compare?
Java Techniques explained:
Since Strings are objects, the equals(Object) method will return true if two Strings have the same objects. The == operator will only be true if two String references point to the same underlying String object. Hence two Strings representing the same content will be equal when tested by the equals(Object) method, but will only by equal when tested with the == operator if they are actually the same object.
So, I went through the program again and I realised that all the strings are predefined in the program. There is not even a single string is created during runtime (using "new String") and being compared to other strings.
However, to be safe, most of the time, programmers should use ".equals" rather than "==" to avoid unexpected outcome. It simply because ".equals" will compare 2 strings character by character to determine equality while "==" checks whether 2 string objects are identical. Try to do this experiment and you will understand:
String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);
It returns false, while the following code returns true.
String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));
This is just a reminder to Java programmers, also to me.
If my article helped you solved your problem, consider buy me a beer!
Share this article: del.icio.us | digg it
Tags: java, Programmers should read
Related posts: