I'm trying to replicate this in Java. To save you the click, it says that a character array ['F', 'R', 'A', 'N', 'K', NULL, 'k', 'e', 'f', 'w']
, when converted to a null-terminated string, will stop after 'K'
, since it encounters a null pointer there. However, my Java attempts don't seem to be working.
public class TerminatingStrings{
public static void main(String[] args){
char[] broken = new char[3];
broken[0] = 'a';
broken[1] = '\u0000';
broken[2] = 'c';
String s = new String(broken);
System.out.println(s);
}
}
Still prints ac
. Aside from this I've also tried (1) not initializing broken[1]
and (2) explicitly setting it to null, at attempt which didn't even compile.
Is this possible at all in Java? Or maybe my understanding of things is wrong?
The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0'). When we write some string using double quotes (“…”), then it is converted into null terminated strings by the compiler.
the null character is used for the termination of array. it is at the end of the array and shows that the array is end at that point.
The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0. The null terminator of a wide-character string consists of one gl_wchar_t character whose value is 0.
C strings are null-terminated. That is, they are terminated by the null character, NUL . They are not terminated by the null pointer NULL , which is a completely different kind of value with a completely different purpose.
Unlike C, Java does not use NUL-terminated strings. To get the behaviour, your code has to find the location of the first \0
in the char array, and stop there when constructing the string.
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