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

All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.

Moderators: Site Manager, fjwalraven

Post Reply
ETS User

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

Post by ETS User »

The Question stated:

Code: Select all

What will the following code print?


  int i = 0;
  int j = 1;
  if( (i++ == 0) [b]&&[/b] (j++ == 2) )
  {
     i = 12;
  }
  System.out.println(i+" "+j);
In the explanation the answer stated:

Code: Select all

This question is based on 2 concepts:

1. i = = ++j is not same as i = = j++;
In the case of i == ++j, j is first incremented and then compared with i. While in the case of i == j++;, j is first compared with i and then incremented.

2. The | operator, when applied for boolean operands, ensures that both the sides are evaluated. This is opposed to || which does not evaluate the RHS if the result can be known by just evaluating the LHS.

Now, let us see the values of i and j at each step:

int i = 0;
int j = 1;
if( (i++ == 0) [b]&[/b] (j++ == 2) )    //compare i with 0 and increment i => returns true and i becomes 1. Evaluate next condition:
		//compare j with 2 and increment j => return false and j becomes 2.
		//true & false returns false so i= 12 is not executed.
{
	i = 12;
}
System.out.println(i+" "+j)); //print 1 and 2
This is not the same. The answer should be: 12 1 in stead of 1 2

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

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

Post by admin »

Hello,
I just ran the code and it prints 1 2 as stated. Could you please specify why it should print 12 1?

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

Guest

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

Post by Guest »

yes, the explanation is misleading. The answer ist still correct but for a differetn reason: the && operator does not ensure that both the sides are evaluated. But in this case it needs to evaluate the second side also as the first side comes out as true.

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

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

Post by admin »

I see the problem. You are right. The explanation is not for this question. This has now been fixed.

thank you for your feedback!
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 28 guests