Strings and things
Written by Antoni Boucher   
Article Index
Strings and things
Solution
When are two strings equal? It sounds like an easy question but it's much more difficult when objects enter the picture as this Java brain-teaser demonstrates.

When are two strings equal? It sounds like an easy question but it's much more difficult when objects enter the picture.

Java is an object-oriented programming language which uses an object to represent string instead of a character array. A string isn't a primitive data type in Java.

Some people compare String objects the same way as other primitive types (with the == operator).

But, is it the right to do it?

 

Banner

 

Background

Every Java programmer knows how to compare primitive types (int, boolean, char, etc.) with the == operator:

public class Equality {
 public static void main(String[] args) {
  int a = 10, b = 10;
  if(a == b) {
   System.out.println("Equal");}
  }
 }

But what about String objects?

The following snippet shows we can compare String objects in the same way:

public class StringEquality {
 public static void main(String[] args) {
  String string = "abc", string2 = "abc";
  if(string == string2) {
   System.out.println("Equal");
  }
 }
}

And this works. This sort of  early experience with comparing strings can lead beginners astray.

So is it always true that you can compare strings with the equality relational operator?

Puzzle

If you use the == operator to compare String objects, you may have had trouble with it, if not it is only a matter of time. For example try the following:

public class StringEquality {
 public static void main(String[] args) {
  String string1 = "abc", string2 = "def";
  if(string1 + string2 == "abcdef") {
   System.out.println("Equal");
  }
 }
}

In this case the  string comparison does not work...

The comparison:

string1 + string2 == "abcdef" 

seems to be false when by all reasonable logic it should be true.

Here is another example that does not work:

public class StringEquality {
 public static void main(String[] args) {
  String string1 = "abc";
  String string2 = new String("abc");
  if(string1 == string2) {
   System.out.println("Equal");
  }
 }
}

Again the result is false when in fact that strings should be the same and so you would expect the comparison to be true..

Why are these two comparisons false when we would expect them to be true?

Go to the next page to see the answer.

 

<ASIN:0470889640>

<ASIN:0132354764>

<ASIN:0071606300>

<ASIN:0596009208>



 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.