Senin, 22 Juli 2013

Java Mysteries

If you aren't a computer nerd -- you might want to skip this one.

I have started to use the FindBugs plugin for Eclipse, and it is very nice.  It finds many obscure failures that Eclipse or MyEclipse alone does not.  One particular problem it found in the code that I am attempting to brutalize into usefulness was use of == and != operators for doing String compares.  If you program in Java, you immedately recognize that:

    if (strObject == "hello")

is wrong.  String compares are done with

   if (strObject.equals("hello")

But we had almost 200 string compares using == or !=.  So why do we not have more problems?  The always useful StackOverflow explains why this often works, in spite of being wrong.  Java is smart enough to create a single copy of a String if it is a constant and there is another constant of the same content.  As a result, == and != will work if you are comparing two String objects that are both constants.  Thus, the many compares of the form strObj == "" work because the passed in parameter strObj was initialized somewhere to "".  If for any reason strObj is created in some other manner, such as new String(""), or as the result of some concatenation operation, the use of == or != is not going to work correctly.

As a result, in many cases, these really invalid uses of == and != work -- but it is a hazardous practice!


Tidak ada komentar:

Posting Komentar