English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm trying to compare two strings in an if statement, one is buffer.toString the other is "sequence", the name of the other string variable. right now my if statement loooks like (buffer.toString() == sequence), but it doesn't work. I also tried sequence.toString(). i know it is only comparing addresses, not the actual string.

2006-10-23 11:23:36 · 4 answers · asked by snoboarder2k6 3 in Computers & Internet Programming & Design

4 answers

for string comparisons in java don't use '==' use sequence.toString().equals(buffer.toString())

2006-10-23 11:30:03 · answer #1 · answered by wooster 2 · 1 0

Java strings are immutable therefore the JVM, as an optimization maps all strings with the same contents to the same instance. Therefore unlike just about any other object the "==" operator will work because if they have the same contents they will have the same reference handle. You could alternatively compare their hash codes, or use the .equals() method. One problem might be other characters in the StringBuffer new lines and other white space are big culprits.

Note .NET does a similar thing with strings so the same reasoning applies.

2006-10-23 19:11:38 · answer #2 · answered by run4ever79 3 · 0 0

run4ever79 was partly correct. String literals and constants are interned automatically. But Strings created in other ways are not. It would not be good performance-wise if all Strings were always interned. Only those that need to be should be interned.

The following
StringBuffer buf = new StringBuffer();
buf.append('h').append('e').append('l').append('l').append('o');
String s = buf.toString();
String t = "hello";
System.out.println("s == t : " + (s==t));

returns "s == t : false"

It will say "true" if you do this change:
String s = buf.toString().intern();

Do so carefully, and only where it warrants. See the documentation for java.lang.String.intern().

2006-10-24 15:29:17 · answer #3 · answered by vincentgl 5 · 0 0

If (string1 == string2)
This is an exactly equal compare of objects. In this instance you are comparing the address of string1 with the address of string2.
This is why it does not work.
The == operator will only work on basic element types like numbers.

The test can either be
if (sequence.equals(buffer.toString()))
or
if (buffer.toString().equals(sequence))
This one works because the toString() returns a string and you can add the equals() method to a string.

Have fun

2006-10-23 19:02:35 · answer #4 · answered by AnalProgrammer 7 · 1 0

fedest.com, questions and answers