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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With