Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble understanding order of execution in a java algorithm (k= and ++k) [duplicate]

Tags:

java

algorithm

I've had to do a Java exam recently, and was wondering about one of the questions I had wrong. The question was as follows:

What will the following code print when run without any arguments ...

public class TestClass {

    public static int m1(int i){
        return ++i;
    }

    public static void main(String[] args) {
        int k = m1(args.length);
        k += 3 + ++k;
        System.out.println(k);
    }

}

With the answers being a number between 1 and 10. My original answer was 7, whereas they state that the correct one is 6.

My logic:

m1 sets k to 1, as it's ++i and thus gets incremented prior to returning.
then the += is unrolled, making: 'k = k + 3 + ++k'.
++k is executed, making k 2.
Replace the variables with their value: 'k = 2 + 3 + 2'
k = 7.

However, they state it as k = 1 + 3 + 2. Could anyone explain as to why the variable is replaced first, before performing the ++k?

like image 869
Joey van Gangelen Avatar asked Nov 28 '16 10:11

Joey van Gangelen


2 Answers

The post and pre increment operators do operate on a temporary value which is getting assigned after the equation. Which means that

i = 0;
i = i++ // still 0
i = ++i // 1

Because the right hand side is temporary and do not reflect the left side before the assignment.

With your logic this would result in

int i = 0;
i = ++i // 2 - wrong.
like image 126
Murat Karagöz Avatar answered Sep 27 '22 22:09

Murat Karagöz


Without any arguments means args.length = 0

int k = m1(args.length); m1 (0) = ++0 = 1

So k = 1

k += 3 + ++k;

k = k + 3 =4. ++k = ++1 = 2

So

4 + 2 = 6

like image 44
M.Sarmini Avatar answered Sep 27 '22 21:09

M.Sarmini