-4

What is the difference between a String "\0" and a String "" ? Both are null but there must be some difference, so what is it?

duffymo
  • 305,152
  • 44
  • 369
  • 561
Torrtuga
  • 37
  • 1
  • 7

4 Answers4

5

The first one is a String containing a single character, whose value is 0.

The second one is a String containing 0 character.

None of them are null. Objects can't be null. References to objects can be.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • from http://stackoverflow.com/questions/9753576/whats-the-meaning-of-char-zero-0-in-java , The character '\0' is the null character. It's a control character. so is your statement that first string value is 0. Is that correct ? Though i am not sure what null character means . – M Sach May 03 '15 at 13:14
  • the first String's value is not 0. The single character contained in the first string has the value 0. `char` is a numeric type, whose values go from 0 to 2^16 - 1. The "null character" is the character whose value is 0. The 'a' character is the character whose value is 97. – JB Nizet May 03 '15 at 13:44
  • Thanks JB Nizet. Got you partially. Its kind of (char)(0) . But as its a control character(non printable), what can be practical use of it. I understand \t is also non printable character but when i print it , it displays tab space but i am not sure how \0 helps practically ? – M Sach May 03 '15 at 14:00
  • You can imagine using it as a separator in a network protocol, or when you send messages to a hardware device that gives it some special meaning. Read http://en.wikipedia.org/wiki/Null_character – JB Nizet May 03 '15 at 14:04
1

Both of these strings are not null, because there's a special null value in Java which means absence of any object. The "" string is actually empty, and the string with single \0 character is not empty. Its length is 1, for example. And they are not equal to each other.

Unlike C/C++ \0 symbol is perfectly valid in Java strings.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

None of them are null, first String contains "\0" and second string is an empty string . If you invoke length method on firstString you will get 1 and 0 on second string

sol4me
  • 15,233
  • 5
  • 34
  • 34
0
    String n1="\0";
    String n2="";
    System.out.println("\n"+n1.length()+"\n"+n2.length());

Output:

1

0

n1 has single character where n2 is an empty string.

Mohan Raj
  • 1,104
  • 9
  • 17