0

When I execute:

String a = "hello";
String b = "hello";
System.out.println(a==b);

I get output as "true".

But when I run:

String a = new String("hello");
String b = "hello";
System.out.println(a==b);

I get output as "false".

I understand that in the first case, Java makes 'b' point to the same object where 'a' pointed, but why can't it do that in the second case?

  • Because you are explicitly telling it to create a new object. – racraman Jan 31 '20 at 05:58
  • @racraman Yes, but only for 'a'. While creating 'b', Java should search for an object already containing "hello" and that to 'b' - as it did it in the first case. – Kunal Jain Jan 31 '20 at 06:00
  • This is definitely a duplicated question.. – user3437460 Jan 31 '20 at 06:04
  • In short, `==` compares references, `.equals()` compares your String content. – user3437460 Jan 31 '20 at 06:06
  • `Java should search ... as it did it in the first case. ` No, it shouldn't, since that would have a (big) impact on runtime speed. In the first case, the "search" does NOT happen at runtime but at compile time against compile-time constants, and so there is no impact on runtime speed. – racraman Jan 31 '20 at 06:09

2 Answers2

2

String in Java are immutable. Meaning:

String a = "hello";
String b = "hello";

a and b are litterally pointing to the same object in memory

Here you explicitly create a new object

String a = new String("hello");
String b = "hello";

Hence the 2 are not equal.

== compares the memory address. To check if an Object is equal to another in Java you should use the equals method that is on all objects.

If you rewrite System.out.println(a==b); to System.out.println(a.equals(b)); it will be true for both cases

Leon
  • 12,013
  • 5
  • 36
  • 59
0

Please read the following well explained answer on stackoverflow:
What is the difference between "text" and new String("text")?

Tarun
  • 3,162
  • 3
  • 29
  • 45