简体   繁体   中英

the difference of String.valueOf(char) and +

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

A char is not a String. In your first print statement you are converting the char to a string and then printing the value. In the second line you're just printing the value of the char directly.

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 operator String + char is compiled to java.lang.StringBuilder#append(char) , so you are directly appending a character to the buffer, rather that creating a temporary String .

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.

You haven't initialized the value of a, so it is equivalent to char a = 0; a non-printable character.

Initialize the value to something lets say static char a = 'a'; That should show you something.

Update: as the second character is non-printable it is displayed as a square but it is in fact a '\\0' character.

Update 2: The default value is 0, as in the number 0, not the character '0'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM