简体   繁体   English

String.valueOf(char)和+的区别

[英]the difference of String.valueOf(char) and +

to show the default value of char ,I wrote code like this: 为了显示char的默认值,我编写了如下代码:

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. 在第一个打印语句中,您将char转换为字符串,然后打印该值。 In the second line you're just printing the value of the char directly. 在第二行中,您只是直接打印char的值。

As user1681360 mentioned, it is the character '\\0' you are printing. 如user1681360所述,它是您要打印的字符'\\0' You have not initialized your field, so Java initializes it for you to the default value, unprintable character '\\0' . 您尚未初始化字段,因此Java会为您将其初始化为默认值,即不可打印字符'\\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. 在第一行中,您首先创建一个String ,然后附加它。 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 . 在第二行中,运算符String + char被编译为java.lang.StringBuilder#append(char) ,因此您直接将字符附加到缓冲区,而不是创建临时String

Indeed the two approaches are always equivalent, even when the character in question is '\\0' . 实际上,即使所讨论的字符是'\\0' ,这两种方法也始终是等效'\\0' The character '\\0' has a special treatment in Java Language Specification, but that does not affect this particular behavior. 字符'\\0'在Java语言规范中有特殊处理,但是不影响此特定行为。

You haven't initialized the value of a, so it is equivalent to char a = 0; 您尚未初始化a的值,因此它等效于char a = 0; a non-printable character. 不可打印的字符。

Initialize the value to something lets say static char a = 'a'; 将值初始化为某种东西,可以说成静态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. 更新:由于第二个字符不可打印,因此显示为正方形,但实际上是'\\ 0'字符。

Update 2: The default value is 0, as in the number 0, not the character '0'. 更新2:默认值为0(如数字0),而不是字符“ 0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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