Khayelihle Tshuma
Khayelihle Tshuma

Reputation: 31

Java : Operator Precedence when methods are involved

Kindly assist. I am preparing for the Java 7 Programmer 1 exam and came across this question in one of the enthuware Tests.

Question :

Consider the following method:

static int mx(int s) { for(int i=0;i<3;i++) { s=s+i; } return s; }

And the following code snippet:

`   int s=5;
    s += s + mx(s) + ++s;
    System.out.println(s);` 

What will it print ?

End Question

According to the rules on operator precedence , I started by evaluating ++s getting a value of 6 for s, followed by using 6 in the mx method to get a value of 8. Next I added 6+8+6 =20. Then finally carried out the assignment operation as s = 6+ 20 = 26.

The correct answer is 24. I cannot seem to figure out how they come to that answer. Kindly shed some light.

Upvotes: 2

Views: 100

Answers (2)

ankh-morpork
ankh-morpork

Reputation: 1832

The value of s does not change on the ++s because the evaluation of the expression is left to right.

You can check this by modifying your code like this:

public static int  mx(int s){
    System.out.println(s);
    for(int i=0;i<3;i++){
        s=s+i;
    }
    return s;
}

public static void main(String[] args){
    int s=5;
    s += s+mx(s)+ ++s;
    System.out.println(s);
}

The print statement in mx(int s) will print out the value for s, revealing that it is still 5.


Additionaly, if mx(int s) had been passed the value 6 it would return 9 instead of 8.

Upvotes: 0

Eran
Eran

Reputation: 393851

You shouldn't start with ++s, since the evaluation is from left to right.

s += s + mx(s) + ++s;

is the same as

s = 5 + 5 + mx (5) + 6;

which is

s = 5 + 5 + 8 + 6 = 24

Upvotes: 5

Related Questions