java - String.valueOf(int i) 和只打印 i 的区别

标签 java string casting value-of

请看下面的代码片段:

int count = 0;
String query = "getQuery"; 
String query1 = "getQuery";
final String PARAMETER = "param";

query += "&" + PARAMETER  + "=" + String.valueOf(count);
query1 += "&" + PARAMETER  + "=" + count;
System.out.println("Cast to String=>"+query);
System.out.println("Without casting=>"+query1);

两个输出完全一样。 所以我想知道,当我们仅使用 count 就可以获得相同的结果时,为什么要使用它。

我得到了一些链接,但没有发现完全相同的混淆。

最佳答案

这在 JLS - 15.18.1. String Concatenation Operator + 中有很好的解释:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

您应该注意以下几点:

The + operator is syntactically left-associative, no matter whether it is determined by type analysis to represent string concatenation or numeric addition. In some cases care is required to get the desired result.

如果你写 1 + 2 + "fiddlers" 结果将是

3 fiddlers

但是,编写 "fiddlers "+ 1 + 2 会产生:

fiddlers 12

关于java - String.valueOf(int i) 和只打印 i 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36549270/

相关文章:

java - 如何使用 Java 在 Selenium RC 中使用 xpath

java - DAO 和 hibernate 的区别

c++ - 从 C++ 中的二进制文件读取不同字节顺序的整数

返回未定义的javascript字符串长度

java - 为什么我的listView不可见?

java - 运算符重载 STL 的性能损失是什么

python-3.x - 如何计算包含字符串子列表的列表中特定字符的出现次数?

java - 如何打印文件中以条件字符串开头和结尾的某些行

ruby - 双引号与单引号

C99 : cast double to struct?