Java Zero to All All questionsPractise free
Interview questions › Practice Programs — Master Every Pattern › Strings — Practice Programs

Why should you never compare strings with == , and when is it a subtle trap?

Level II · JuniorStrings — Practice Programs
Short answer

== compares references (are these the same object), not contents.

Explanation

String literals are interned into a shared pool, so "a"=="a" happens to be true, which lures beginners into thinking == compares text. But new String("a") == "a" is false, and any runtime-built string (concatenation, input, StringBuilder.toString()) is a distinct object, so == fails. Always use equals() for content, or equalsIgnoreCase() to ignore case.

Common mistakes
  • Comparing strings with ==.
  • Relying on interning for correctness.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Strings — Practice Programs.

Practise free

More on Strings — Practice Programs