Does java define string as null terminated?

前端 未结 3 1672
挽巷
挽巷 2020-12-03 18:20

As my title suggests, it\'s a theoretical question. I\'d like to know that if java defines string as null terminated.

相关标签:
3条回答
  • 2020-12-03 18:36

    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() or GetStringUTFChars(). GetStringChars() is not documented as returning null-terminated data, so you shouldn't assume that it's null-terminated—you must use GetStringLength() to determine its length. Likewise with GetStringUTFChars(), you must use GetStringUTF8Length() to determine its length in modified UTF-8 format.

    0 讨论(0)
  • 2020-12-03 18:38

    I'd like to know that if java defines string as null terminated.

    No. A String is defined to be a fixed length sequence of char values. All possible char values (from 0 to 65535) may be used in a String. There is no "distinguished" value that means that the string ends1.

    So how they track string ending? Using length?

    Yes. A String object has a private length 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".


    1 - As noted, neither the JLS or the javadocs for String specifically that a String implementation cannot use NUL termination. However, the fact that all characters including NUL are significant in a String means that NUL termination is not practical.

    0 讨论(0)
  • 2020-12-03 18:48

    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:

    public static void main(String[] args) {
        String s = "Juned";
        System.out.println(s);
    }
    

    Debugger screenshot:

    enter image description here

    0 讨论(0)
提交回复
热议问题