Lulzim Fazlija Lulzim Fazlija - 1 year ago 36
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 Source
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.