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 String
s. However, the output surprised me.
This is x - .
This is y - .
false
If these two String
s are NOT equal, then how could they produce the same output?
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
.
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.
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