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?
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?
Yes. And always prefer the 2nd option.
The first one creates an unnecessary string instance. The string literal (two quotes around a string) creates a string object itself. Then, if you use the first option, another, unnecessary instance is created.
When you use only the string literal (the 2nd option), the jvm uses a table where it stores canonical string objects. So for all strings declared with "Samuel"
there will be only one instance in the JVM. But if you use the String(str)
constructor, you'll have more instances, which means more memory.
To answer a follow-up question in the comments: this is only valid for strings. All other objects are created through constructors, as they don't have a designated literal.
For example, you needCar car = new Car("honda", "civic")
. Simply having ("honda, "civic")
isn't a valid syntax - it can't be known what type are you creating.
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 immutable they are interned and drawn from the same pool.
Thus, s1 == s2
will be false and s1.equals(s2)
will be true. The difference between is that first type of declaring string is called "String Literal" and second type of declaring string is called "String object." String literal is used to optimize the use of memory and efficiently manages the memory.