简体   繁体   中英

How is memory allocated for a string?

How is memory allocated for a string, say in Java or C++? This might be silly, so please excuse me. I'm wondering because a string is of unknown size.

Java Strings are immutable objects. In a way each time you create a String, there will be char[] memory allocated with number of chars in String. If you do any manipulations on that String it will be brand new object and with the length of chars there will be memory allocation done.

In Java, String is an immutable Object, so the "size" of the String has to be known at time of allocation. It'll end up allocated in a shared object pool if it's "static" (eg a String litteral, like "Hey, I'm a String litteral!" ), or on the heap if it's constructed using new String(...) .

Internally, a java String is nothing more than a char array with a known length. Here are the class members of String :

  110   public final class String
  111       implements java.io.Serializable, Comparable<String>, CharSequence
  112   {
  113       /** The value is used for character storage. */
  114       private final char value[];
  115   
  116       /** The offset is the first index of the storage that is used. */
  117       private final int offset;
  118   
  119       /** The count is the number of characters in the String. */
  120       private final int count;
  121   
  122       /** Cache the hash code for the string */
  123       private int hash; // Default to 0
  124   
  125       /** use serialVersionUID from JDK 1.0.2 for interoperability */
  126       private static final long serialVersionUID = -6849794470754667710L;
            ...

It is dynamically allocated like a vector. When it becomes too big, it is resized automatically by an internal method (C++). In Java, as thinksteep already mentioned, Strings are immutable.

You confuse variable size with unknown size . A concrete string in any language has always a known size, its just that each instance of a string may have a different size. How languages deal with the variable length can be very different and is implementation specific.

Just to add to previous answers.
In Java strings can be allocated in two ways depending on how string is created. For example if string is created with String s = "some string"; JVM will put this string in so called literal pool (something left behind from time when memory was problem) and if you create string with String s = new String("some string"); JVM will put this on heap ...
only significant difference is that you may use operator == to compare strings if they are both in literal pool, but this is never recomended.

regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM