Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is a string represented in Java internally?

Tags:

java

string

I know that a C string abc would internally be abc\0 in C, is it the same case with Java?

like image 371
Will Avatar asked Dec 16 '11 02:12

Will


3 Answers

No, it's not the same in Java. There's no null terminator. Java strings are objects, not points to arrays of characters. It maintains the length along with the Unicode characters, so there's no need to look for a null terminator.

You don't have to ask here: look at the source for String.java in the src.zip that ships with your JDK. Here's the start of it:

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;
}
like image 102
duffymo Avatar answered Nov 19 '22 15:11

duffymo


Nope, C strings are an array of chars and thus there is no length associated with them. The side affect of this decision is that to determine a string's length, one must iterate through it to find the \0, which isn't as efficient of carrying the length around.

Java strings have a char array for their chars and carry an offset length and a string length. This means determining a string's length is rather efficient.

Source.

like image 34
alex Avatar answered Nov 19 '22 14:11

alex


String in C language is an array of char type where as in Java it a class and it represents collection of unicode chars.

like image 2
KV Prajapati Avatar answered Nov 19 '22 15:11

KV Prajapati