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?
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.