Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate a char[] -> String conversion midway via a null pointer

Tags:

java

string

null

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?

like image 417
skytreader Avatar asked Jun 07 '12 15:06

skytreader


People also ask

How do you null terminate a string?

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.

How do I terminate a char array?

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.

What is the null terminating character?

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.

Are char pointers null-terminated?

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.


1 Answers

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.

like image 77
NPE Avatar answered Oct 22 '22 15:10

NPE