This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Could some one explain the follwoing..

 
R .sourav nayak
Ranch Hand
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
do {} while loop will print three times zero. It do something first and then evaluating the condition.
 
shilpa Reddy
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your code is the same as:



Hope it helps
 
Radoslaw Sztando
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your code is the same as:



Hope it helps
 
Gayathri Ramanujam
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);

}}
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic