/kb

personal knowledgebase

Archive for the ‘strings’ tag

Strings and equality in Java

without comments

In order to compare objects in Java we are taught to use the equals()-method, except when the goal is to check for object reference, explicitly, then the == operator must be used. However, String objects does not behave entirely as expected, as seen from the following example.

  String s1 = "Fish";
  String s2 = "Fish";
 
  String s3 = new String("Fish");
  String s4 = new String("Fish");
 
  System.out.println(s1 == s2);       // true
  System.out.println(s1.equals(s2));  // true
 
  System.out.println(s3 == s4);       // false
  System.out.println(s3.equals(s4));  // true

The reason for this behaviour is that strings s3 and s4 are created outside of the string pool. In the string pool, String objects with the same value are set to the same object internally in order to save space.

Written by HÃ¥vard Grimelid

June 4th, 2008 at 1:32 pm

Posted in Programming

Tagged with ,