About Question com.enthuware.ets.scjp.v6.1.821 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.1.821 :

Post by ETS User »

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

Code: Select all

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; //1
        System.out.println(k);
    }

}
k = 1 + 3 + 2; (at this point value of k is 2 because of ++k). But the value of RHS has not yet been assigned to k.
So that means that the JVM computes the "++k" first, before computing the rest of the statement? Is there some kind of rule that applies here?

Thank you

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.1.821 :

Post by admin »

Yes, there is a difference between k++ and ++K.
Try running these statements separately and see the output:

int x = 0, k=0;
x = k++;
System.out.println(x+" "+k); //should print 0 and 1.


int x = 0, k=0;
x = ++k;
System.out.println(x+" "+k); //should print 1 and 1.

The difference is because in case of k++, the value of the expression (i.e. k++) is evaluated first (which equal to 0, because k is 0 at this point) and then k is incremented to 1. The value of the expression, which was just computed as 0 is assigned to x. In case of ++k, k is incremented first and then the value of the expression ++k is evaluated, which is now 1 and so 1 is assigned to x.

http://www.coderanch.com/t/385399/java/ ... Evaluation
If you like our products and services, please help us by posting your review here.

Guest

Re: About Question com.enthuware.ets.scjp.v6.1.821 :

Post by Guest »

Hi,

There is a mistake in the explanation of this question:
It is stated there that k += 3 + ++k; could be expanded to k = k + 3 + ++k;

The proper way of expanding this is however: k = (k + 3 + ++k);
In this question it doesn't matter - but it is an important issue.

Cheers,
Tom

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.1.821 :

Post by admin »

Hi,
I don't think there is any difference between k = k + 3 + ++k; and k = (k + 3 + ++k);
Can you please explain?

thanks,
Paul.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 104 guests