Reputation: 14520
I just want to know, In java how many memory locations will it take to assing to string variables with same value.
For Example :
String name1 = "Test";
String name2 = "Test";
Will this take 2 memory locations or only 1 since the values are equal in JAVA. Thanks
Upvotes: 1
Views: 135
Reputation: 4307
Here is an article about the String usage in JVM : Memory usage of Java Strings and string-related objects
For reasons we'll explore below, the minimum memory usage of a Java String (in the Hotspot Java 6 VM) is generally as follows:
Minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)
Or, put another way:
String.subString()
will return a new string, but the two strings share the inner char array.Upvotes: 1
Reputation: 122006
String
literals are stored in a common pool.
This facilitates sharing of storage for strings with the same contents to conserve storage.
So one location for both.
Upvotes: 4
Reputation: 35577
There is only one memory location there and both name1
and name2
will refer that location.
If you do following way, There are two memory location for name1
and name2
String name1 = new String("Test");
String name2 = new String("Test");
Upvotes: 1
Reputation: 2102
only one because once you declare variable name
and assign value as "Test" after that if same value you are assigning to different variable it will still point to same unless and until you explicitly create new object of string with same value.
Upvotes: 1
Reputation: 45070
Thanks to String-intern'ing, all the compile time constants will go into the String intern pool and thus, only 1 "Test"
would be created in the pool which will take up only 1 memory location.
And both name1
and name2
will be assigned with the same reference from the pool.
Upvotes: 2
Reputation: 62864
This will occupy only one memory location.
String name1 = "Test";
String name2 = "Test";
The reason is that both name1
and name2
refer to the same String in the inter pool.
If you had something like:
String name1 = "Test";
String name2 = new String("Test");
then, two different object would be created.
Upvotes: 1