5

Possible Duplicate:
How do I compare strings in Java?
Java string comparison?

import java.util.*;

public class whatever
{

    public static void main(String[] args)
    {

        Scanner test = new Scanner(System.in);
        System.out.println("Input: ");
        String name = test.nextLine();

        if (name == "Win")
        {
            System.out.println("Working!");
        }

        else
        {
            System.out.println("Something is wrong...");
        }

        System.out.println("Value is: " + name);

    }

}

The code above is pretty self-explanatory. I'm assuming == can only be used for numbers? I want "Working!" to be printed.

0

2 Answers 2

9

== compares objects by reference.

To find out whether two different String instances have the same value, call .equals().

Sign up to request clarification or add additional context in comments.

1 Comment

Just to mention, "Win".equals(name) will be a more secure solution in case if name is null.
5

You should use

if (name.equals("Win")){
    System.out.println("Working!");
}

Edit Suggested By RC in comments to avoid null problems:

if ("Win".equals(name)){
    System.out.println("Working!");
}

2 Comments

"Win".equals(name) so if name is null, no worries
I'd recommend ignoring case. Should "win" be less a victory than "Win" or "wIn" or "wiN"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.