wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Could some one explain the follwoing.. 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 "Could some one explain the follwoing.." Watch "Could some one explain the follwoing.." New topic
Author

Could some one explain the follwoing..

R .sourav nayak
Ranch Hand

Joined: May 14, 2006
Posts: 67
class JMM111 {
public static void main (String[] args) {
int j = 0;
for (int i = 0; i < 2; i++) do
System.out.print(i);
while (j++ < 2);
}}

What is the result of attempting to compile and run the program?

a. Prints: 0001
b. Prints: 012
c. Prints: 012012
d. Prints: 012345
e. Prints: 001122
f. Prints: 1112
g. Prints: 111222
h. Prints: 121212
i. Run-time error
j. Compile-time error
k. None of the above


Answer is A: 0001. why?
thanks in advance,
reena
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
do {} while loop will print three times zero. It do something first and then evaluating the condition.
shilpa Reddy
Ranch Hand

Joined: Jul 26, 2006
Posts: 42
hi...

jus watch that you have embedded a do while loop inside a forloop...

so first time it will enter into the do loop it will print the value tobe 0, then in will check for the while condition which will be 0 < 2....so The CATCH point here is it will execute only the do loop and not the for loop till j is 2...so only 0 will get printed...when j>2 for loop will be executed wherein i becomes 1....

i guess you understand..
Radoslaw Sztando
Ranch Hand

Joined: Mar 11, 2004
Posts: 40
your code is the same as:



Hope it helps


Regards,
Radek Sztando
Radoslaw Sztando
Ranch Hand

Joined: Mar 11, 2004
Posts: 40
your code is the same as:



Hope it helps
Gayathri Ramanujam
Greenhorn

Joined: Aug 14, 2006
Posts: 4
The for statement executes the first statement after the for since there are no {}
the first statement after the for is the do
so its because of the do statement that the print happens..and when it goes to the next iteration of the do then println does not execute...because j>2
try this and it should be clear

class A {
public static void main (String[] args) {
int j = 0;

for (int i = 0; i < 2; i++)
do
{
System.out.print(" J:" + j);
System.out.print(" I:" + i);
}
while (j++ < 2);

}}
 
GeeCON Prague 2014
 
subject: Could some one explain the follwoing..