Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings with \0 behave weird in Java

Why is a different to b?

    String a = "BuildGUID10035\0528\0440";
    String b = "BuildGUID10035" + '\0' + 528  + '\0' + 440;

    System.out.println("A: " + a);
    System.out.println("B: " + b);
    System.out.println(a.equals(b));
like image 948
Schifty Avatar asked Jul 30 '26 17:07

Schifty


2 Answers

They are different because in the first string, \052 gets interpreted as a single octal escape sequence (and so is \044).

The following two strings do compare equal:

String a = "BuildGUID10035\000528\000440";
String b = "BuildGUID10035" + '\0' + 528  + '\0' + 440;

(I've replaced the \0 with \000 in a.)

like image 197
NPE Avatar answered Aug 01 '26 07:08

NPE


\052 and \044 are octal representations of characters. Anything starting with \ and three digits are considered as octal forms of characters. Hence, two strings are not equal.

like image 37
Drona Avatar answered Aug 01 '26 08:08

Drona