• Post Reply Bookmark Topic Watch Topic
  • New Topic

Mysterious if statement  RSS feed

 
Richard Mateosian
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am still on chapter 1 of Head First Java, but I took a little detour to write the following class:

public class Make {
public static void main (String[] Args) {
String word;

if (Args.length < 1) {

word = "sense";

} else {

word = Args[0];

// Debugging printout
System.out.println("***" + word +"*** " + word.length());
}

if (word == "joke") {

System.out.println ("There are three guys at an insane asylum.");
System.out.println ("The first says `I'm Napolean!'");
System.out.println ("The second says `how do you know?'");
System.out.println ("`God told me' says the first guy.");
System.out.println ("`I did not!' says the third.");

} else {

System.out.println("Don't know how to make " + word);
}

}
}


It compiles OK. When I run it I get the following output (including the debugging printout):

c:\JavaPlay\ejprog>Java Make
Don't know how to make sense

c:\JavaPlay\ejprog>Java Make fudge
***fudge*** 5
Don't know how to make fudge

c:\JavaPlay\ejprog>java Make joke
***joke*** 4
Don't know how to make joke

c:\JavaPlay\ejprog>


What I expected to see in the last case was the five lines of the joke. I don't understand why my if statement isn't working as I expect it to.


Thanks for your help.

EJ
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at this line of code:

Here you are comparing two String references. The "gottcha" is that you are comparing the REFERENCES, not the actual String objects. In otherwords, this is comparing if the variable word is "pointing" to the same memory location where the String constant "joke" is stored.

In order to do the comparison you expect, you should use the equals() method:



This will compare the contents of the Strings rather than the memory locations. So the moral of the story is to use equals() to compare objects, not ==.

Layne
 
Richard Mateosian
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the tip, without it I wouldn't have gotten it to work.


EJ
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!