Why does Java's == not work for comparing two strings with the same value?

Clock Icon

asked about 1 year ago

Message Icon

1

Eye Icon

81

I am learning Java and I wrote this code:

1String a = new String("hello");
2String b = new String("hello");
3System.out.println(a == b); // prints false
1String a = new String("hello");
2String b = new String("hello");
3System.out.println(a == b); // prints false

I expected this to print true because both strings have the same content. Why does == not work here?

1 Answer

The == operator compares object references, not their contents. Even though both a and b contain "hello", they are two separate objects. Use .equals() instead:

1System.out.println(a.equals(b)); // true
1System.out.println(a.equals(b)); // true

If you want to compare memory references, use ==. For content comparison, always use .equals().

1

Write your answer here