11

Possible Duplicate:
Java string replace and the NUL (NULL, ASCII 0) character?

I'm doing some String algorithms in Java, and i noticed that wherever i include a char with the value of 0 (zero) it marks the end of the String. Like this:

String aString = "I'm a String";
char[] aStringArray = aString.toCharArray();
aStringArray[1] = 0;
System.out.println(new String(aStringArray)); //It outputs "I"

What's the reason/cause of this behaviour?

Community
  • 1
  • 1
Carlos Gavidia-Calderon
  • 7,145
  • 9
  • 34
  • 59

3 Answers3

20

The character '\0' is the null character. It's a control character, and it does not terminate the string, that's not how strings work in Java (that's how they work in C, though.)

Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

For some additional insight, add the following to you code:

 System.out.println(new String(aStringArray).length());
 for (Byte b : new String(aStringArray).getBytes()) {
     System.out.print("["+b+"]"); 
 }

Your rendering system (console or output window) is not displaying everything.

Java42
  • 7,628
  • 1
  • 32
  • 50
0

I'm wondering if you have posted your actual code. When using the String(byte[]) constructor the actual length of the string is dependent on the contents of the array.

M Platvoet
  • 1,679
  • 1
  • 10
  • 14