我有以下简单的Java代码,试图理解使用'+'运算符的java中的字符串连接方式。
function calculateChange(){
var amountDue = document.getElementById('amount-due').value;
var amountReceived = document.getElementById('amount-received').value;
////////////////////////////////////
//dollars to print dollar mount
dollars = Math.floor(amountReceived % amountDue);
document.getElementById("dollars-output").innerHTML = dollars;
var quarters = Math.floor(amountReceived% dollars);
document.getElementById('quarters-output').innerHTML = quarters;
// var quarters to print # of quarters in change
var dimes = Math.floor(amountReceived% dollars);
document.getElementById('quarters-output').innerHTML = dimes;
// var dimes to print # of dimes in change
///////////////////////////////////////
var nickels = Math.floor(amountReceived% dollars);
document.getElementById('quarters-output').innerHTML = nickels;
//var nickels to print # of nickels in change////////////////////////////////////
//math.floor to do math
//var pennies to print # of pennies in change
var pennies = Math.floor(amountReceived% dollars);
document.getElementById('quarters-output').innerHTML = pennies;
return;
// to return the output of code
}
public class Problem {
public static void main(String... args){
String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object
System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false
}
}
是2个字符串文字(str4
和ab
)的结果,而c
是2个字符串文字(str5
和{ {1}})。在这两种情况下,java都将调用StringBuilder类来执行串联。
我相信这会导致在Java堆空间中创建2个不同的StringBuilder对象。
如果我的理解是正确的,为什么str2
返回true?有人可以帮我弄清楚吗?
关于, 曼尼什·沙玛
答案 0 :(得分:0)
这取决于编译器和jvm如何对此进行优化。仅当两个变量都经过优化以指向相同的地址时,评估才是正确的。通常,使用==比较字符串是不可靠的。请改用“等于”方法。