• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KB page no 336 return statement

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

friends please explain me the following code why it is printing the output one time??

static boolean doStuff() {
for (int x = 0; x < 3; x++) {
System.out.println("in for loop");
return true;
}
return true;
}

Thanks in advance
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A return statement causes execution to immediately leave the method.
 
vaibhav mishra
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since your method signature says that method should return boolean so as soon as your method encounters a return method it's task is completed and it returns true and exit form method however if you remove first return statement you will get what you expect

boolean yourMethod()
 
chander shivdasani
Ranch Hand
Posts: 206
Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As soon as the return statement is encountered, the control is passed to the block that called this method.

It is immaterial to place the return statement in a for loop as it will be executed only once.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic