Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

A very very strange problem

I encountered a very strange problem in my java program.

part of the source code:
... ...
String token = st.nextToken();
System.out.println("token="+token);
boolean abc = false;
if (token=="asdf") abc = true;
System.out.println("abc="+abc);

The result displayed in the console is:
token=asdf
abc=false

It's really strange! Since the first result has demonstrated that the value of token is "asdf", how can the statement (token=="asdf") be false?
[561 byte] By [WXY595] at [2007-11-11 7:41:07]
# 1 Re: A very very strange problem
Believe it or not, this isn't that strange, nor is it a problem :D

This happens because a String is an Object, not a primitive data type. When you do:

if (new String("a") == new String("a")) {
System.out.println("a == a");
}

It will not be true. What this is actually doing is checking the memory location. The two Strings will have a different memory location, therefore making it false.

The String class has an equals(String) method for what you want do to:

if (new String("a").equals(new String("a"))) {
System.out.println("a == a");
}
destin at 2007-11-11 22:37:34 >
# 2 Re: A very very strange problem
Thanks a lot for your help. You are really helpful. The equals method does work properly.
WXY595 at 2007-11-11 22:38:45 >
# 3 Re: A very very strange problem
This code:

public class StringTest {
public StringTest() {}
public void doIt () {
String a="a";
String b="a";
if (a==b)
System.out.println("a==b");
}

public static void main(String[] args) {
StringTest st=new StringTest();
st.doIt();
}
}

..produces this output:

a==b

I am no expert on the javac but it appears that code optimization in closely knitted code makes the strings a and b share the same memory location cause they are identical.
sjalle at 2007-11-11 22:39:43 >
# 4 Re: A very very strange problem
really good explanation. thanks very much
WXY595 at 2007-11-11 22:40:43 >
# 5 Re: A very very strange problem
Yeah. When you do

String a = "a";
String b = "a";

a and b point to the same place in memory. But if you do:

String a = new String("a");
String b = new String("a");

a and b reference different places in memory.
destin at 2007-11-11 22:41:41 >
# 6 Re: A very very strange problem
My point was that this occurs only in closely knitted code as a result of compiler optimization.

String a = "a";

and

String a = new String("a");

are programatically identical, but the compiler bypasses the optimization for last one.
sjalle at 2007-11-11 22:42:45 >