• Post Reply Bookmark Topic Watch Topic
  • New Topic

Trouble with String.equals( String) and ==  RSS feed

 
Juha Makinen
Greenhorn
Posts: 2
Debian Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was working through Just Java 2 when I stumbled on a problem. Frankly, it is giving me a headache...
Anyone with some idea what is going on?

Now:

String A="end";
String B="end";

if( A ==B ) /* whatever */;
if( A.equals( B ) /* whatever */;

ought to work the same, only they do not. Here is cut-and-paste of the output I get:

£
£ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Server VM (build 20.1-b02, mixed mode)
£
£ javac problem.java
£ java problem
aaa
aaa
ffffff
ffffff
444
444
end
I don't see why
£

and the program producing it:

// I don't get it. Why this ?

import java.util.*;
import java.io.*;

public class problem {

public static void main( String args[] ) {

Scanner doRead = new Scanner( System.in);
String doneRead = null;
while( ( doneRead = doRead.next() ) != (String)"end" ) {
doneRead.trim();
if( doneRead.equals( "end" ) ) { // this DOES work
// if( doneRead == "end" ) { // this DOES NOT work
System.err.println( "I don't see why" );
break;
};
System.out.println( doneRead );
};
}
}


 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to use == only with primitives. For String for checking equality equals() should be used. Since == in case of objects, it checks for the references rather than the original object content.
Read - Oldthread1 and oldthread2
 
Juha Makinen
Greenhorn
Posts: 2
Debian Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.

 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
welcome to the ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!