As we know String
is immutable, which means a new instance is created every time.
My question is that if I write:
System.out.println("Java"+"is"+"programming");
then how many objects are created in pool?
As we know String
is immutable, which means a new instance is created every time.
My question is that if I write:
System.out.println("Java"+"is"+"programming");
then how many objects are created in pool?
Your example will create a single string object in the string pool.
after that, if you do:
String x = "Javaisprogramming";
it will still point to the same object in the string pool. You can read more here
Your example will create a single string object. This is noted throughout the Java documentation.
The way I understand it, Java only adds new strings to the string pool when they're initially created. So,
String str1 = "hello";
Would be a single string in the pool.
So would
String str2 = "Java" + "is" + "cool";
Your Example will create 'single' string only which is
String x = "Javaisprogramming";
because '+' is a string concatenation operator in java(it internally call append()) so when you call System.out.println("Java"+"is"+"programming");
then compiler create one string object from concatenation and send it with println()
method.
for more about '+' operator see this answer