This question already has an answer here:
- how string terminates in java? 2 answers
As my title suggests, it's a theoretical question. I'd like to know that if java defines string as null terminated.
This question already has an answer here:
As my title suggests, it's a theoretical question. I'd like to know that if java defines string as null terminated.
Java strings are not terminated with a null characters as in C or C++. Although java strings uses internally the char array but there is no terminating null in that. String class provides a method called length to know the number of characters in the string.
Here is the simple code and its debugger contents:
Debugger screenshot:
No. A String is defined to be a fixed length sequence of
char
values. All possiblechar
values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends.Yes. A
String
object has a privatelength
field (in all implementations I've examined ...).If you want to understand more about how Java strings are implemented, the source code for various versions is available online. Google for "java.lang.String source".
Does it matter?
If you convert a Java string into some kind of serialized format (onto disk, the network, etc.), then all that matters is the serialization format, not the JVM's internal format.
If you're reading the string's data in C code via JNI, then you never read the data directly, you always use JNI functions like
GetStringChars()
orGetStringUTFChars()
.GetStringChars()
is not documented as returning null-terminated data, so you shouldn't assume that it's null-terminated—you must useGetStringLength()
to determine its length. Likewise withGetStringUTFChars()
, you must useGetStringUTF8Length()
to determine its length in modified UTF-8 format.