Lulzim Fazlija Lulzim Fazlija - 2 months ago 5
Java Question

What is the difference between these two ways of initializing a String?

String obj = null;
obj= new String("Samuel");

//vs

String obj = null;
obj="Samuel";


Is there any difference between these two ways of initializing a String?

Answer
String obj = new String("Samuel");
String obj1 = new String("Samuel");

//vs

String obj = "Samuel";
String obj1 = "Samuel";

in the first case obj==obj1 returns false

in the second case obj==obj1 returns true.

The reason for that is that in the first case you have two references to two different Objects. In the second case you have one object since Strings are interned and are drawn from the same pool.