Reputation: 3621
Strings are immutable because they are stored in a constant string pool. So, where are stringbuilder objects created ? Say, I create two string builder objects
StringBuilder s1 = new StringBuilder("abc");
StringBuilder s2 = new StringBuilder("abc");
I will be ending up with 2 separate objects in heap memory right both containing the values "abc" ?
Upvotes: 5
Views: 3837
Reputation: 306
String literals that are created with double quotes are created in the String literal pool.
StringBuilder Objects are always created in the Heap memory.
Upvotes: 0
Reputation: 30723
The constant pool stores strings that are defined as literal (enclosed in double quotes) in the source code.
Non literal strings are not stored in the CP. They simply use an underlying char
array, and make sure it is never written to.
A StringBuilder allocates such an array and then hands it over to a newly-created String object.
Upvotes: 0
Reputation: 1500065
The immutability of strings has little to do with there being a constant string pool. Or rather, they have to be immutable for a string pool to be useful, but there doesn't have to be a string pool for them to be immutable.
Note that only compile-time constants end up in the string pool usually - unless you call intern()
. So for example, if you have:
char[] x = { 'a', 'b', 'c' };
String s1 = new String(x);
String s2 = new String(x);
then s1
and s2
refer to equal strings, but distinct objects.
Creating two StringBuilder
objects simply creates two objects though. The exact implementation details of what's inside a StringBuilder
can easily change between versions, and I don't know the details offhand, but it could easily be a char[]
created from the string passed into the constructor. (I believe that's the case for JDK 1.6, anyway.)
Upvotes: 5
Reputation: 4546
String str1 = "Java"
String str2 = "Java"
So, str1 and str2 are pointing to the same "Java" in literal pool.
String str3 = new String("Java");
String str4 = new String("Java");
str3 and str4 are not pointing to the same location but have separate memory allocated.
StringBuilder s1 = new StringBuilder("abc");
StringBuilder s2 = new StringBuilder("abc");
s1 and s2 do not point to same memory location.
So, whenever you say "new", it creates a separate memory for that variable.
You can test this by displaying their address on the Console.
Upvotes: 1