It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes loop 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 "loop" Watch "loop" New topic


Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
For the following code, the answer given is 121212
class JMM110 {
public static void main (String[] args) {
int j = 0;
do for (int i = 0; i++ < 2
while (j++ < 2);

Can anybody pl explain?Thanks
[ May 22, 2004: Message edited by: Barry Gaunt ]

Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
I did a proper indentation for the code you've posted in order to make it easier to understand.

Pay attention for the following:
1) do-while loop is always executed at least once.
2) i++ and j++ return its old value, then increment it.

Knowing this, give it another shot, and trace it again. If you still can't understand the answer, i'll explain it more in detail.
[ May 22, 2004: Message edited by: Vicken Karaoghlanian ]

- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. - What truth? - That there is no spoon!!!
Voggy Horla

Joined: Dec 23, 2003
Posts: 13
the conditional expression
(i++ < 2)
will be executed before print the i.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
A good approach to understanding such problems is to run the code. You can also put additional print statements in to check the values of the variables i and j. There is also the technique of using a symbolic debugger such as that provided by the free Eclipse IDE. And there is also the java debugger jdb.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Sridhar Srinivasan
Ranch Hand

Joined: Nov 07, 2003
Posts: 117
I understood.Thanks a lot!
I agree. Here's the link:
subject: loop
It's not a secret anymore!