2
String str1 = "apple";
String str2 = "apple";

System.out.println(str1 == str2);

Why does the 3rd line return true? I thought you couldn't compare strings like that

I understand that compareTo should be used for strings, why can I do ==

joshmeranda
  • 3,001
  • 2
  • 10
  • 24
yEs
  • 27
  • 3
  • 1
    Does this answer your question? [Why does == return true for a String comparison?](https://stackoverflow.com/questions/25978510/why-does-return-true-for-a-string-comparison) – joshmeranda Apr 01 '22 at 17:45

2 Answers2

3

Because '==' is used to compare the reference of the objects

String string1 = new String("apple");
String string2 = new String("apple");

// Is false, they are two different objects
string1 == string2;

// Is true, their value are the same
string1.equals(string2);

// Is true because java uses the same object if you don't create a new one explicitly
"apple" == "apple";
Rob
  • 320
  • 1
  • 10
0

Read this chapter of the article and you will understand.

The behavior you observe has to do with String literals where the JVM usually optimizes the storage by creating new literals if they don't already exist, otherwise providing the existing reference.

This should not be the way that you handle Strings though as they are still objects and you want to compare them by their content and not their memory reference which is what is happening when you use == .

This is why oracle explicitly advices for Strings to be compared using the equals method. There are many cases where a different object reference would be returned for some string that already exists in memory.

Check the following example to see one of those cases

  public static void main(String[] args) {

        String str1 = "apple";
        String str2 = "apple";
        System.out.println(str1==str2);        //prints true

        String str3 = "apple2";
        String str4 = str3.replaceFirst("2","");

        System.out.println(str1);              //prints apple
        System.out.println(str4);              //prints apple
        System.out.println(str1==str4);        //prints false
        System.out.println(str1.equals(str4)); //prints true

    }
Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
  • https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer – jonrsharpe Apr 01 '22 at 17:47
  • @jonrsharpe it was just a quick post with the main reason for why this was happening which was intended to be enriched in some seconds with an example which I was already testing. Please check my updated answer – Panagiotis Bougioukos Apr 01 '22 at 17:57
  • So wait "some seconds" and post when it _is_ an answer, or post a comment. – jonrsharpe Apr 01 '22 at 18:09