请看下面的代码片段:
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/