I know that a C string abc
would internally be abc\0
in C, is it the same case with Java?
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;
}
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.
String in C language is an array of char type where as in Java it a class and it represents collection of unicode chars.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With