Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #8
See Also: JBuilder Papers

To be or not to be equal
Usually when we want to compare different values we use the == operator. But this operator will not always produce the results we may accept.

When we compare values of primitive types, like int, the result of a compare will be predictable. For example:

  /* Compare two ints */
  int firstInt  = 42;
  int secondInt = 42;

  System.out.println((firstInt == secondInt));  /* returns true */
Trouble starts when we want to compare different objects, and object instances. If we compare two different object references using the == operator, we will only get true if they reference the same object in memory. But if we don't want to compare object references but object values, we must use the equals method. Every object has got this method, because it is defined in java.lang.Object. But to be useful the object must have over written this method. Let's take a look at an example with Strings:
  1:     /* Compare two Strings */
  2:     String firstString  = "JBuilder 2.0 rocks!";
  3:     String secondString = "JBuilder 2.0 rocks!";
  4:
  5:     System.out.println((firstString == secondString));  /* returns true */
  6:
  7:     /* Compare two Strings */
  8:     firstString  = new String("JBuilder 2.0 rocks!");
  9:     secondString = new String("JBuilder 2.0 rocks!");
 10:
 11:     System.out.println((firstString == secondString));  /* returns false */
 12:
 13:     System.out.println((firstString.equals(secondString)));  /* returns is true */
The results in line 11 and 13 are predictable. Line 11 returns false, because we are comparing two different object instances, and they aren't the same. The variables firstString and secondString point to two different objects in memory. So in order to test if the strings inside the String object are the same, we must use the equals method (line 13).
But what about the true result of line 5? Here we see some compiler optimazation at work. Because the secondString variable contains the same string as the firstString variable, the compiler already assumes both variables can point to the same space in memory. And because both variables point to the same memory space, the comparison returns true. But we cannot rely on this process for other objects, so try to use the equals method, when comparing objects.


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.