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
I believe that the underlying mechanism for creating a String is a StringBuilder which assembles the String object at the end. At least I know for sure that if you have a string that you want to change, for example:
String str = "my String";
// and then do
System.out.println(str + "new content");
So what this does is it creates a StrigBuilder from the old object and replaces it with a new one that is constructed from the builder. This is why it is more memory efficient to use StringBuilder instead of a regular string to which you would just append stuff.
There is a way to access the already created pool of String which is by using the String.intern() method. It tells java to use the same memory space for Strings which are the same and gives you a reference to that place in memory. This also allows you to use the == operator to compare strings and is more memory efficient.