Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the null literal?

Tags:

java

string

I have written the following program.

public class StringTest {
    public static void main(String[] args){
        String x = "\0";
        String y = " ";
        System.out.println("This is x - "+x+".");
        System.out.println("This is y - "+y+".");
        System.out.println(x.equals(y));
    }
}

Of course, x.equals(y) should clearly be false, as they are completely different Strings. However, the output surprised me.

This is x -  .
This is y -  .
false

If these two Strings are NOT equal, then how could they produce the same output?

like image 362
JavaNewbie_M107 Avatar asked Dec 06 '22 06:12

JavaNewbie_M107


2 Answers

If these two Strings are NOT equal, then how could they produce the same output?

They just look like the same output ... on your console!

If you redirected the console output to a file and examined with a hexadecimal dump tool, you will probably1 find that they are different.

1 - We can't be certain of that. It is also possible that the process of encoding the characters in the platform's default charset is mapping the NUL to a SP. But a hex dump will clarify this.


By the way, null is what people normal mean by "the null literal" in Java. What you have is a String literal ... whose only character is the Unicode code-point 0x0000.

like image 128
Stephen C Avatar answered Dec 22 '22 07:12

Stephen C


Having the same ouput (optically) doesn't mean that the string consists of the same chars. E.g. a tab looks the same as four spaces. In UTF-8 there are a lot of chars that look exactly the same but aren't.

This could also apply just to the representation on your console. Even if the null character should look differently your console might be showing it wrongly.

like image 30
André Stannek Avatar answered Dec 22 '22 07:12

André Stannek