The reason is string interning. It's complicated. The compiler is "smart" enough to use the same exact object for s1 and s2, even though you might think they are different. But s3, which uses new String("Arsalan")
, doesn't intern.
Some guidelines:
- You should almost always use equals(), not ==, to compare strings
- You should almost never use
String s = new String("foo")
.
Instead, use String s = "foo"
.