I was curious as to why Strings can be created without a call to new String(), as the API mentions it is an Object of class java
String s="hi"for the first time what really takes place ?Does the JVM replace it like this
String s=new String("hi"), wherein an Object is created and "hi" is added to the String literal pool and so subsequent calls such as String s1="hi" are taken from the pool ?.
No. What really happens is - the String Literals are resolved during compile time and interned (added to the String constants pool) as soon as the class is loaded / initialized or lazily. Thus, they are made available to the classes within the JVM.
Note that, even if you have a String with value "hi" in the Strings constants pool, new String("hi") will create another String on the heap and return its reference.
- is
String s=new String("Test");
String s1="Test";
the same as
String s="Test";
String s1="Test";
in terms of memory utilization and efficiency?
No, in the first case 2 "Test" Strings are created. One will be added to the String constants pool (assuming it is not already present there) and another on the heap. The second one can be GCed.In the second case, only one String literal is present in the String constants pool and there are 2 references to it (s and s1).
- Also if there any way by which we can access the String Pool as in check how many String literals are present in it, space occupied etc from the program or from any monitoring tool?
I don't think we can see the contents of the String constants pool. We can merely assume and confirm the behavior based on our assumptions.