Eldhose M Babu
Eldhose M Babu

Reputation: 14520

How many memory locations will it take?

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

Answers (6)

lichengwu
lichengwu

Reputation: 4307

Here is an article about the String usage in JVM : Memory usage of Java Strings and string-related objects

How to calculate String memory usage

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:

  • multiply the number of characters of the String by two;
  • add 38;
  • if the result is not a multiple of 8,
  • round up to the next multiple of 8;
  • the result is generally the minimum number of bytes taken up on the heap by the String.

  • if the string is in PermGen, thow String will occupy only one space.
  • if not, two String will occupy twice space.
  • besides, String.subString() will return a new string, but the two strings share the inner char array.

Upvotes: 1

Suresh Atta
Suresh Atta

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

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

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

shreyansh jogi
shreyansh jogi

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

Rahul
Rahul

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

Konstantin Yovkov
Konstantin Yovkov

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

Related Questions