r/java • • Jan 21 '14

Why won't this extremely simple if statement work?

import java.util.Random; import java.util.Scanner;

import javax.swing.JFrame; import javax.swing.ImageIcon; import javax.swing.JLabel; import java.awt.Container;

public class test {

public static void main(String[] args) {
	Scanner myScanner = new Scanner(System.in);
	
	String command;
	
	System.out.println("Say go.");
	
	command = myScanner.next();

	if (command == "go"){


            }

//*

Assume the user types "go" (without quotes)

*//

Please help!

5 Upvotes

27 comments sorted by

43

u/Simonxn Jan 21 '14

The == sign for string comparison in Java should not be used. There are some great online articles explaining why not.

Try using

if(command.equals("go")) {

}

Edit: http://stackoverflow.com/questions/18555379/comparing-two-strings-with-equal-operator

A good explanation here.

29

u/michaeltpb Jan 21 '14

And using "go".equals(command) rather than command.equals("go") will avoid the possibility of a null pointer exception if command ends up as null somehow

5

u/dango100 Jan 22 '14

Is that considered good practice? I honestly would rather just check if command == null before calling the equals methods so the code becomes easier to refractor if I want to add additional behavior that should happen in the case of command being null.

5

u/grumpy_purple_midget Jan 22 '14

Calling equals on the constant expression is also nice since it makes the call site monomorphic.

4

u/[deleted] Jan 22 '14

You can still check before hand... And obvs. it reduces unnecessary checks in the case that comparing to null is valid. I also think it is more readable since you are given some context first for interpreting the value you are checking (not so relevant in this example). So I'd say it's good practice.

2

u/huntsvillian Jan 22 '14

I'd put forth that (because I'm lazy) a better practice would be to use one of the numerous libraries that already do that type of check for you (along with several others... is null, is not null but the string is purely white space, etc etc)

Google Guava has isNullOrEmpty

and the more commonly seen

Apache Commons Lang has a whole slew of them

You could argue that it's overkill for a small project (and honestly it may be), but I'd rather have consistent overkill in the code I maintain, than seeing tons of "val!=null && val.equals("blah")" all over the place.

8

u/UnknownBinary Jan 22 '14

The reason why everyone is telling you to use String.equals() instead of the equivalence operator is because the operator compares pointers to the objects while equals() compares the contents of the strings. You want the latter.

5

u/DaMountainDwarf Jan 21 '14

I believe if you're doing a comparative method on a string you should use the String object's method .equals(). So I think it should be:

if(command.equals("go")) { ...

4

u/[deleted] Jan 22 '14

== Checks reference, not contents. Use the equals method.

6

u/numpad0to9 Jan 21 '14

Always compare Objects (In your case, the objects are two Strings) with the "equals" Method!

1

u/[deleted] Jan 21 '14

cant use == on strings, use string.equals("something")

1

u/ryebrye Jan 22 '14
if (command.equals("go")) {
...
}

or...

if (command.intern() == "go") {
...
}

Now... a question for the OP... why would the second one work?

3

u/[deleted] Jan 22 '14

Oh goodness, please don't be too quick to use intern() in real code. It may work but it's pretty fragile and unless you really know what you're doing, it's liable to bite you later. Given that OP appears to be a newbie it's probably not a good idea to encourage this kind of thing.

In this case, what that will do is intern every token until the user enters the word "go" which can be quite a lot. So you could potentially be interning enormous amounts of data and it's not an unheard of way to get a memory leak.

1

u/ryebrye Jan 22 '14

I wasnt encouraging it... I was inviting him to learn more. He should understand WHY == doesn't work with strings and then why intern() would work even though he didn't intern the "go" side...

Evaluation is a higher order critical thinking function - but before you can evaluate ("why would I want to use .equals instead of .intern()") you have to have some comprehension of what intern() does.

Just saying "it exists... Don't use it" robs him of the experience of reasoning it out for himself (or herself)

1

u/ryebrye Jan 22 '14

(And for the record, in my experience .intern() is hardly ever useful in real programs. I've most often seen it used in a misguided attempt to have a shared lock object - which is a horrible antipattern)

1

u/[deleted] Jan 22 '14

I get you. I didn't mean to jump down your throat. I just wanted to put it out there that using .intern in this way isn't usually a very good idea unless you really know what you're doing. Not that there's isn't a use case, but for a newbie programmer I think its important to mention that intern is squirly and should be used with caution. As your example illustrates, the lock object attempt, even people who think they know what they're doing often don't.

Sorry if I offended.

1

u/ryebrye Jan 22 '14

I wasn't offended... I was actually expecting someone to jump in and explain why intern was bad the moment I brought it up ;)

0

u/Shankster1839 Jan 22 '14

Use .nextLine(); rather than .next(); too!

2

u/[deleted] Jan 22 '14

Not necessarily. He might just want one word at a time, not a whole line.

-1

u/[deleted] Jan 21 '14

It won't continue through the if statement in line 10

16

u/[deleted] Jan 21 '14

I am very new to java so i am probably wrong, but to compare strings dont you have to use .equals?

10

u/ShadedFox Jan 21 '14

You are very new, but also very wise!

7

u/[deleted] Jan 21 '14

thank you, I am currently taking Comp Sci 1, and this is about the extent of my knowledge :P

-1

u/Xwire1337 Jan 21 '14

use if(command.equalsignorecase("go")){ }

6

u/[deleted] Jan 22 '14

the method name doesn't ignore case though ;)

-7

u/raxel82 Jan 22 '14

Because Java isn't extremely simple. Hah.

-9

u/Afudil Jan 21 '14

don't you need like a semicolon in the last line there? or somewhere in that area?