Thursday, January 13, 2011

Assignment and Equality in Java

Summary: Because Java uses reference semantics, there are potential errors that can occur with the assignment statement and the equality operator.





Java programmers make mistakes in the use of the assignment and equality operators, especially when strings are used. The concept of reference semantics is (or should be) explained in detail in your textbook, so we limit ourselves to a reminder of the potential problems.

String equality

Given:
String s1 = "abcdef";
String s2 = "abcdef";
String s3 = "abc" + "def";
String s4 = "abcdef" + "";
String s5 = s1 + "";
String t1 = "abc";
String t2 = "def";
String s6 = t1 + t2;
all strings sn are equal when compared using the method equals in the class String that compares the contents pointed to by the reference:
if (s1.equals(s5))         // Condition evaluates to true
The string literal"abcdef" is stored only once, so strings s1s2 and (perhaps surprisingly) s3 and s4 are also equal when compared using the equality operator == that compares the references themselves:
if (s1 == s3)              // Condition evaluates to true
However, s5 and s6 are not equal (==) to s1 through s4, because their values are created at runtime and stored separately; therefore, their references are not the same as they are for the literals created at compile-time.
Always use equals rather than == to compare strings, unless you can explain why the latter is needed!

Assignment of references

The assignment operator copies references, not the contents of an object. Given:
int[] a1 = { 1, 2, 3, 4, 5 };
int[] a2 = a1;
a1[0] = 6;
since a2 points to the same array, the value of a2[0] is also changed to 6. To copy an array, you have to write an explicit loop and copy the elements one by one.
To copy an object pointed to by a reference, you can create a new object and pass the old object as a parameter to a constructor:
class MyClass {
  int x;
  MyClass(int y) { x = y; }
  MyClass(MyClass myclass) { this.x = myclass.x; }
}
 
class Test {
  public static void main(String[] args) {
    MyClass myclass1 = new MyClass(5);
    MyClass myclass2 = new MyClass(myclass1);
    myclass1.x = 6;
    System.out.println(myclass1.x);  // Prints 6
    System.out.println(myclass2.x);  // Prints 5
  }
}
Alternatively, you can use clone as described in Java textbooks.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

java

Popular java Topics