In some (usually in C) implementations of strings, the 'length' of a string is tracked by way of a sentinel character, generally: '\0'. The contract is:
- The actual character '\0' cannot be in the string.
- The '\0' char is the terminator; it is not itself part of the string and signals the end.
This is not how java works, at all, though.
There are other ways to encode string length. For example, first, you store the length of the string, then you store that many bytes. In bytes, imagine this is in memory:
many bytes ... 0x00 0x00 0x00 0x05 0x48 0x65 0x6C 0x6C 0x6F ... many more bytes
Then, given a pointer to that first 0x00, code can figure out that is "Hello". You have a hypothetical way of storing strings that works just great. However, scanning for 'the ending 0x00' is not going to work because this particular way of storing strings doesn't have that.
The above is close to how java works. However, as further complication, java is java. java does not do pointers. It is not possible to get a memory pointer pointing to that length field.
Conclusion: What you want to do? Not possible. There is no \0 to find, and you can't read the memory containing the length. It's abstracted away; if you want length, you invoke stringInstance.length(). End of story.
There are of course, creative, silly, and entirely academic ways to do it. For example:
public int getStringLengthInAStupidWay(String in) {
int i = -1;
try {
while (true) input.charAt(++i);
} catch (IndexOutOfBoundsException inevitable) {}
return i;
}
You can even make that O(logn) with some fancy maths. I have absolutely no idea what possible point there'd be to this, though.
lengthmethod to find the length of a string.