Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a String object

Tags:

java

oop

I don't understand why you create a String object as follows:

String stringObj = "";

I think, it should be:

String obj = new String();
like image 644
ThiepLV Avatar asked May 04 '26 11:05

ThiepLV


1 Answers

String stringObj = "";

Is called as String literals. They are interned.

What that means is, let us say if you have

String stringObj = "";
String stringObj2 = "";
String stringObj3 = "";

All 3 references (stringObj, stringObj2, stringObj3) points to same memory location.

String obj = new String();

This syntax creates new String object on every invocation.

What that means is, let us say if you have:

String stringObj = new String();
String stringObj2 = new String();
String stringObj3 = new String();

Three new (separate) String objects will be created and point to different memory locations.

like image 122
kosa Avatar answered May 06 '26 01:05

kosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!