0

I'm new to Java, and am having trouble understanding why the if/else statement in this code seems to believe the strings a and c are not equal.

public class Main {
    public static void main(String[] args) {
        String a = "foo";
        String b = "Foo";
        String c = b.toLowerCase();

        System.out.println(c);

        if (a == c) {
            System.out.println("Strings are equal");
        }
        else {
            System.out.println("Strings are NOT equal");
        }
    }
}

Here is the output:

foo
Strings are NOT equal

I'm using www.learnjava.org and their webservice to compile/execute code, if that matters.

Thanks

Adam Hughes
  • 14,601
  • 12
  • 83
  • 122
  • 4
    You're active enough in the community, I would expect you to know to search SO prior to asking a question. – CubeJockey Aug 21 '15 at 20:14
  • Ya, sorry I thought the error was in the `toLowerCase` method, and searched that. I took it for granted that `==` was equivalent by value, as the guide I'm using is doing it for integers. – Adam Hughes Aug 21 '15 at 20:16

1 Answers1

1

You shall not compare Strings with ==, as this only compares if they are the SAME object, but not if they are EQUAL.

String x = "abc";
String y = x;
String z = "abc";

boolean a = x == y; // true
boolean b = x == z; // can be false (unless the compiler optimizes it, but you shouldn't rely on that)
boolean c = x.equals(z); // true - this is the right way to compare Strings
Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
  • Ahh, so exactly the opposite of Python? – Adam Hughes Aug 21 '15 at 20:14
  • 3
    For questions like this, use the duplicate closing reason instead. No matter what answer you would put here, it would not exceed the combined thoroughness of the answers in the canonical Q+A one. – Jeroen Vannevel Aug 21 '15 at 20:14
  • 2
    I'm not the one who downvoted, but answering these types of questions that clearly have been answered too many times already is not helping anyone. Please vote to close instead. – Keppil Aug 21 '15 at 20:15
  • @Adam you should instead use the [`String.equalsIgnoreCase(String s)`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)) method. – CubeJockey Aug 21 '15 at 20:15
  • 1
    Ok, I'll close it, sorry. Actually, I can't close quesiton until this answer is removed – Adam Hughes Aug 21 '15 at 20:18