to show the default value of char ,I wrote code like this:
public class TestChar {
static char a;
public static void main(String[] args) {
System.out.println("."+String.valueOf(a)+".");
System.out.println("the default char is "+a);
}
}
but the console output is confused.the first is “. .” ,however the second is “the default char is [](like this ,I don’t know how to describe it.)” why?thanks for help
As user1681360 mentioned, it is the character
'\0'you are printing. You have not initialized your field, so Java initializes it for you to the default value, unprintable character'\0'. Depending on the environment, unprintable characters will be shown as empty boxes, question marks, etc.In the first line you are first creating a
String, then appending it. In the second line the operatorString + charis compiled tojava.lang.StringBuilder#append(char), so you are directly appending a character to the buffer, rather that creating a temporaryString.Indeed the two approaches are always equivalent, even when the character in question is
'\0'. The character'\0'has a special treatment in Java Language Specification, but that does not affect this particular behavior.