How is a string represented in Java internally?

I know that the string C abc will be inside abc\0 in C, is this the same case with Java?

+6
source share
7 answers

No, C strings are an array of characters and therefore length is not associated with them. The side effect of this solution is that to determine the length of the string, scroll it to find \0 , which is not so effective for wrapping the length around.

Java strings have a char array for their characters and carry offset length and string length. This means that determining the length of a string is quite effective.

Source

+7
source

No, this is not the same in Java. There is no null terminator. Java strings are objects, not points of character arrays. It supports length along with Unicode characters, so there is no need to look for a null delimiter.

You do not need to ask here: look at the source for String.java in src.zip that comes with your JDK. Here is its beginning:

 public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; /** Cache the hash code for the string */ private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L; } 
+10
source

String in C is an array of type char, where, as in Java, it is a class and is a collection of unicode characters.

+2
source

Not. Null terminators are used in C because it is easier than going around the pointer and size. In Java, size is always known, so a null terminator is not needed. In addition, there are no trailing characters in Java (placing in \0 will be part of a literal string).

+2
source

Java strings do not have a zero sequence, like C strings. This is because Java stores string lengths. You can get the length using String.length() .

+2
source

The String class is implemented in Java. See the OpenJDK implementation for an example.

The OpenJDK 7 String class contains an array of type char[] for storing the string itself, as well as the offset (message of the first used position in char[] ), the length of the string, and the hash code of the string.

It also has two static fields, a version identifier for serialization purposes and an ObjectStreamField[] because of a special wrapper in relation to the serialization output stream (at least in OpenJDK 7).

+1
source

As far as I know, in java String is stored as an object in the heap section as a subclass of the class. There is no need to use '\ 0' to specify only characters or a string.

0
source

Source: https://habr.com/ru/post/903881/


All Articles