5

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.