• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

for loop problem

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic