Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong answer with Addition

Tags:

java

object

oop

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?

like image 375
Youssef N Avatar asked Oct 15 '19 20:10

Youssef N


1 Answers

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()));
like image 122
azurefrog Avatar answered Oct 09 '22 12:10

azurefrog