Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Dan Chisholm Mock Exam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Dan Chisholm Mock Exam " Watch "Dan Chisholm Mock Exam " New topic

Dan Chisholm Mock Exam

Gerald Spica
Ranch Hand

Joined: Jul 28, 2003
Posts: 30
I am confused on a control question,
class JMM110 {
public static void main (String[] args) {
int j = 0;
do for (int i = 0; i++ < 2
while (j++ < 2);
answer = Prints: 121212
This would make sense to me if it was i++ <= 2 and j++ <= 2, otherwise how does it get to 2 for either test.
Yuriy Grechukhin
Ranch Hand

Joined: Jan 16, 2004
Posts: 41
in both conditional statements you use ++ POSTfix operator. It does the following: first returns the value of a variable, and then increaments it.
so in the for loop i++ < 2 means: compare i to 2, then increament it.
if i is 0 initially this would happen:
is 0 less than 2? yes (the expression evaluates to true)
now add 1 to i (i is 1)
print i (which is 1)
on the next iteration i is 1 so...
is 1 less than 2? yes (the expression evaluates to true)
now add 1 to i (i is 2)
print i (which is 2)
the next iteration breaks out of the loop since 2 is not less than 2
change the postfix ++ to prefix and you'll get the desired results.

The sword of destiny has two blades, one of them is you.
Davy Kelly
Ranch Hand

Joined: Jan 12, 2004
Posts: 384

so in the for loop you see what is happening, you start by making i=0, then check 0 < 2 then increment.
so i=1, 1 < 2 then increment i=2, so output is 12
2 is not less than 2 so check while.
while is o < 2 then increment so start the for loop again from the start so ouptut is: 1212
check while 1 < 2, true, so do the for loop again.
ouptut is 121212 then check while.
2 is not less than 2 so false so stop the do statement.
hope this helps you with the output.

How simple does it have to be???
I agree. Here's the link:
subject: Dan Chisholm Mock Exam
It's not a secret anymore!