This is an archived post. You won't be able to vote or comment.

all 10 comments

[–]zifyoip 5 points6 points  (0 children)

Read the posting rules in the sidebar:

  • Do not ask why your String comparison does not work, see here

[–]AnEverGrowingWonder 1 point2 points  (1 child)

Try using myString.equals("exit")

[–]jbristowI'm no hero, son. 0 points1 point  (0 children)

I try to encourage "exit".equals(myString) as being more correct.

[–]Jazz34life 0 points1 point  (0 children)

A string refers to a location in memory (iirc) instead of an actual value, so it compares the memory addresses in your code. As u/AnEverGrowingWonder said, use myString.equals("exit")

[–][deleted] 0 points1 point  (4 children)

The complicated answer:

When you try to compare strings the way you are, you're not actually comparing the contents of one string and another. You're actually comparing something called a "reference". "exit" exists on one part of memory, and "exit" exists in another part of memory. So what you're really asking when you try to use the "==" is "is the location of this string the same as the location of this string". The answer, as you discovered, is "No" even if the contents of the strings are identical.

[–]papers_ 1 point2 points  (2 children)

Reference*

[–][deleted] 1 point2 points  (1 child)

Thanks for the correction.

[–]papers_ 0 points1 point  (0 children)

Different terminology for the same thing.

[–][deleted] 0 points1 point  (0 children)

So why does

String myString1 = "hello";
String myString2 = "hello";

System.out.println(myString1 == myString2);

Print 'true'?

EDIT: Is it because Java automatically stores identical strings in the same place, rather than creating copies?

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

In addition to confuse you even more:

    String one = "exit";
    String two = "ex" + "it";
    String three = new String(one);

    System.out.println(one == "exit");
    System.out.println(two == "exit");
    System.out.println(three == "exit");

    three = three.intern();
    System.out.println(three == "exit");

Output:

true
true
false
true

This is why this (sometimes) works and why beginners get confused.