Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String object creation

I have been reading Java String object and I had this question -

String x="a";
String y="b";

Does it create two objects in Java?

like image 502
user3717604 Avatar asked Mar 29 '26 23:03

user3717604


1 Answers

Those two lines of code will not create any objects. String literals such as "a" are put in the string pool and made available upon class loading.

If you do

String x = new String("a");
String y = new String("b");

two objects will be created in runtime.

These questions/answers should cover follow-up questions:

  • Questions about Java's String pool
  • How many Java objects are generated by this - new String("abcd")
like image 140
aioobe Avatar answered Apr 02 '26 02:04

aioobe