Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Output of this code  RSS feed

 
Preetha Vasudevan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is from Marcus greens mock exam.The output of this program is it prints from 0 to 9 and a constant output of "go" ..can anyone explain how that happens!!

public class Anova{
public static void main(String argv[]){
Anova an = new Anova();
an.go();
}
public void go(){
int z=0;
for(int i=0;i<10; i++,z++){
System.out.println(z);
}
for(; ;) {
System.out.println("go");
}

}
}
[ October 06, 2005: Message edited by: Barry Gaunt ]
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
0 .. 9 is printed because of the 1'st for loop.
But the second for loo does n't have any conditions , so it enters a infinite loop and exexutes the S.o.P ("go") statement & hence the constant output of "go"
 
Chandrahas Tore
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The first for loop executes for ten times from 0..9, so the output 0..9

In the second for loop no conditional expression is specified. When you don't specify conditional expression in for loop it is always evaluated true. So this is infinite for loop & hence the constant output go

 
Ashok George
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi both the answers are exactly true 0=9 gets printed since the first for loop is executed and the go is infintely printed since the second for loop which is also in go() function runs infintly since we haven't given any condtions for the loop to break thru..
 
Preetha Vasudevan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you .
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!