Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String have a parameter-less constructor in Java? [duplicate]

Tags:

java

string

I was looking into the String API and suddenly I came across one String empty Constructor i.e. we can construct an empty String object using String s = new String()

I wonder is there any use of it?

like image 763
Anand Avatar asked Nov 18 '22 05:11

Anand


1 Answers

Ofcourse.....

String s = new String();

will create a Non-literal String object on the heap, which will be garbage collected.

where as

String s = "" ;

will create a String Literal. This will not be garbage collected ever, if it is reachable through the default loader.

See this link below to a question which I asked. This may not be directly related to your question, but it will certainly help you grasp the concept firmly.

Is String Literal Pool a collection of references to the String Object, Or a collection of Objects

like image 174
Kumar Vivek Mitra Avatar answered Dec 17 '22 04:12

Kumar Vivek Mitra