Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop problem

 
Vineet Sharma
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Hunt M.E Q38
public class Test{
public void add(int a) {

loop: for (int i = 1; i< 3; i++){
for (int j = 1; j < 3; j++){
if (a == 5) {
break loop;
}
System.out.println(i*j);
}
}
}
}

Answers:
A. Generates a Runtime Error
B. Generates a Compilation Error
C. Complains that class has not been instantaited
D. Produces no out put

Answer is D and I verified it. But should it not be B or C?
Also, are the label "loop:" and "break loop" correct to use?
Thanks
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Labeling loops is correct. You can put a label just before an while or for loop and then break or continue from that loop later.
Seems like there is part of the code missing. What is the value passed into the add() method. The code for the add() method is fine, so I would say the answer is D based on the other answers. But you are missing main and the call to add here, so if you tried running this class with java Test you would get a runtime error as it wouldn't be able to find main.
Bill
 
Maja Grabovac
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've seen this question somewhere and the value being passed for a is 5. That is the reason it breaks out of the loop immediately without printing out anything.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic