public class Container {
private int value;
public Container(int value){
this.value=value;
}
public int getValue(){
return this.value;
}
public int sum(Container c){
return this.value+c.getValue();
}
public void main(){
Container c1=new Container(1);
Container c2=new Container(2);
System.out.println("sum: " + c1.getValue()+c2.getValue());
System.out.println("sum: " + c1.sum(c2));
}
}
when I am running this code I am getting the following results:
sum: 12
sum: 3
expected is:
sum: 3
sum: 3
Does anyone know why I am getting these results?
When you use the +
operator with a String
it treats it as concatenation, not addition, and Java evaluates operations from left to right, so "sum: " + c1.getValue()+c2.getValue()
is being evaluated as
"sum: " + 1 + 2
"sum: 1" + 2
"sum: 12"
If you want the integer addition to happen first, you need to add parentheses:
System.out.println("sum: " + (c1.getValue() + c2.getValue()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With