How does a return statement differ from break statement?.
If I have to exit an if condition, which one should I prefer, return or break?
break is used to exit (escape) the for-loop, while-loop, switch-statement that you are currently executing.
return will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break nor return to escape an if-else-statement per se. They are used to escape other scopes.
Consider the following example. The value of x inside the while-loop will determine if the code below the loop will be executed or not:
void f()
{
int x = -1;
while(true)
{
if(x == 0)
break; // escape while() and jump to execute code after the the loop
else if(x == 1)
return; // will end the function f() immediately,
// no further code inside this method will be executed.
do stuff and eventually set variable x to either 0 or 1
...
}
code that will be executed on break (but not with return).
....
}
break is used when you want to exit from the loop, while return is used to go back to the step where it was called or to stop further execution.
No offence, but none of the other answers (so far) has it quite right.
break is used to immediately terminate a for loop, a while loop or a switch statement. You can not break from an if block.
return is used the terminate a method (and possibly return a value).
A return within any loop or block will of course also immediately terminate that loop/block.
You won't be able to exit only from an if condition using either return or break.
return is used when you need to return from a method after its execution is finished when you don't want to execute the rest of the method code. So if you use return, then you will not only return from your if condition, but also from the whole method.
Consider the following method:
public void myMethod()
{
int i = 10;
if(i==10)
return;
System.out.println("This will never be printed");
}
Here, using return causes to stop the execution of the whole method after line 3 and execution goes back to its caller.
break is used to break out from a loop or a switch statement. Consider this example -
int i;
for(int j=0; j<10; j++)
{
for(i=0; i<10; i++)
{
if(i==0)
break; // This break will cause the loop (innermost) to stop just after one iteration;
}
if(j==0)
break; // and then this break will cause the outermost loop to stop.
}
switch(i)
{
case 0: break; // This break will cause execution to skip executing the second case statement
case 1: System.out.println("This will also never be printed");
}
This type of break statement is known as unlabeled break statement. There is another form of break, which is called labeled break. Consider this example -
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++)
{
for (j = 0; j < arrayOfInts[i].length; j++)
{
if (arrayOfInts[i][j] == searchfor)
{
foundIt = true;
break search;
}
}
}
This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").
You can learn more abour break and return statements from JavaDoc.
Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.
Break
for(int i=0;i<5;i++){
print(i)
if(i==2)
{
break;
}
}
output: 0 1
return
for(int i=0;i<5;i++)
{
print(i)
if(i==2)
{
return;
}
}
output: 0 1 3 4
break:- These transfer statement bypass the correct flow of execution to outside
of the current loop by skipping on the remaining iteration
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
}
System.out.println(i);
}
}
output will be
0
1
2
3
4
Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
}
System.out.println(i);
}
}
output will be:
0
1
2
3
4
6
7
8
9
return :-
At any time in a method the return statement can be
used to cause execution to branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which
it is executed. The following example illustrates this point. Here,
return causes execution to return to the Java run-time system,
since it is the run-time system that calls main( ).
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
return;
}
System.out.println(i)
}
}
output will be :
0
1
2
3
4
You use break to break out of a loop or a switch statement.
You use return in a function to return a value. Return statement ends the function and returns control to where the function was called.
break breaks the current loop and continues, while return it will break the current method and continues from where you called that method
Break will only stop the loop while return inside a loop will stop the loop and return from the function.
Return will exit from the method, as others have already pointed out. If you need to skip just over some part of the method, you can use break, even without a loop:
label: if (some condition) {
// some stuff...
if (some other condition) break label;
// more stuff...
}
Note, that this is usually not good style, though useful sometimes.
How does a return statement differ from break statement?.
Return statement exits current method execution and returns value to calling method.
Break is used to exit from any loop.
If I have to exit an if condition, which one should I prefer, return or break?
To exit from method execution use return.
to exit from any loop you can use either break or return based on your requirement.
break just breaks the loop & return gets control back to the caller method.
In this code i is iterated till 3 then the loop ends;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
break;
}
}
}
In this code i is iterated till 3 but with an output;
int function (void)
{
for (int i=0; i<5; i++)
{
if (i == 3)
{
return i;
}
}
}
If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:
if(condition){
//do stuff
if(something happens)
condition = false;
}
This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case
Related
I have a Stack with 3 items and I want to loop over each item. If I do this:
public class Main {
public static void main(String[] args) {
Stack<Integer> s = new Stack<>();
s.add(1);
s.add(2);
s.add(3);
for (Integer num = s.pop(); !s.isEmpty(); num = s.pop()) {
System.out.println(num);
}
}
}
then it only prints out 3 and 2 but not 1. Why is that?
The for loop pops the stack then exits the loop if the stack is empty.
for (Integer num = s.pop(); !s.isEmpty(); num = s.pop()) {
System.out.println(num);
}
Put another way, num = s.pop() is run before the test !s.isEmpty(). So on the final iteration, the stack is empty, therefore the loop body isn't executed.
There are many different ways around this. One thing you could do is use a while loop instead:
while (!s.isEmpty()) {
System.out.println(s.pop());
}
For loop consists of 3 expressions: initialization, termination, increment:
for (initialization; termination; increment) {
//
}
initialization is executed only once
termination is executed each iteration
increment is executed each iteration
In your case you retrieve from the stack twice on the first iteration, hence your problem with a non-printing element.
You might be wondering why does it print 3,2 and not 2,1? That's because increment expression is invoked after (in the very end) each iteration through the loop.
All of sections are optional, so you can iterate this way:
for (; ; ) {
System.out.println(s.pop());
}
... and you will eventually have java.util.EmptyStackException on an attempt to pop an element from already empty stack.
So the most basic way to iterate over a stack with a for loop is to make use of termination statement as a "safe-check":
for (; !s.isEmpty(); ) {
System.out.println(s.pop());
}
... which is basically a more complex and counterintuitive way to write a while-loop:
while (!s.isEmpty()) {
System.out.println(s.pop());
}
Docs:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
The reason is that the stack is already empty, when the condition is evaluated.
Few options(not all) how to correctly pop and print all items:
Do-while loop. As mentioned in comments, will throw EmptyStackException, if the stack is initially empty.
do {
System.out.println(s.pop());
} while (!s.empty());
While loop.
while (!s.empty()) {
System.out.println(s.pop());
}
retry: {
.........
if(xyz < 5) {
continue retry;
}
}
Problem : continue cannot be used outside of a loop
Why iteration of a block is prevented in java?
It's not supported because noone implemented it, presumably because they thought that, well, loops should be implemented with the loop constructs Java provides.
What you want to do can easily be implemented as a while loop if you invert the condition and use break instead:
while (true) {
.........
if(xyz >= 5) {
break;
}
}
Or why not write it as a regular loop without break or continue?
do {
.........
} while (xyz < 5);
Problem : continue cannot be used outside of a loop
continue is used within a loop i.e. for/while/do-while, if statements are conditional code blocks and not loops.
Learn more about code branching statements here:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
The purpose of continue keyword is to skip rest of the code inside loop to start with the next pass of loop. So, by it's purpose, continue would not fit in the contexts outside the loops.
goto could be other option for you to reset (or restart) the code of execution. However the best way could be move such part into a method and use recursion along with return under specific conditions to achieve the purpose you are talking about.
As others have pointed out, labels in Java label loops, and are used to specify which loop to break or continue.
That said, if you really want to write "spaghetti code" you can misuse break and continue like for instance:
public class SillyGotoExmple {
public static void main(String args[]) {
int count, loops;
final int NUM_LOOPS=2;
final int MAX_COUNT=10;
loops=0;
bar: do {
count = 0;
foo: do {
System.out.println(count);
if(++count < MAX_COUNT) {
continue foo;
} else if(++loops < NUM_LOOPS) {
continue bar;
} else {
break bar;
}
} while (true);
} while(true);
}
}
For some more discussion on goto in Java, see e.g. Is there a goto statement in Java?
I'm new to this site and also very new to Java and I'm trying to understand the do while loops
Question: What is the output and why?
public class DoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("i is : " + i);
i++;
} while(i < 1);
}
}
I get that the output is "i is : 1" but I'm trying to understand why. It stops once it hits while because i isn't less that 1, right?
Just trying to get my head around it so any help will be appreciated.
Yes. Correct.
do { } while (condition);
This will perform the code at least once, regardless of the condition. After the first execution it will check the condition, which will evaluate to false (1 is not smaller than 1) and thus it will stop.
Yes, the output is 1 because in a do-while loop the statements within the do block are always executed at least once.
After the do block is executed the i value becomes 2 and the while block is not executed.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once
Yes, the output is
i is : 1
The do-while loop will always execute at least once, because the condition isn't evaluated before the loop is entered; it's only evaluated at the end of each iteration. This is in contrast to the while loop, whose condition is checked before the first iteration as well as after each iteration.
i is 1 at the start, then print occurs, then i is incremented to 2. Then the condition is evaluated -- it's false, so the loop terminates.
The output is just 1 becuase the do causes the loop to execute at least once, but the condition in the while doesn't aloow the loop to reiterate, because i is never less than 1
It is no more 1
public class DoWhile {
public static void main(String[] args) {
int i = 1; // i is 1
do {
System.out.println("i is : " + i); //still i is 1
i++; // this makes i = 2;
} while(i < 1);
}
}
if you notice the comments it is no more 1 after the first iteration
Is there ever a situation where you must use a do while loop? Is it an accepted practice? It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}
vs
int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times
The same?
EDIT: I have seen the java doc, but
the example in the java docs doesn't look like it requires that the particular routine inside of the do while loop must be run in the do while loop instead of inside of a regular while loop!
Is there ever a situation where you must use a do while loop?
No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.
Is it an accepted practice?
If you use it appropriately, then yes absolutely.
It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
That's right. You can read more about do-while in its tutorial.
This example maybe help you be clearer:
int i = 3;
System.out.print("while: ");
while (--i > 0){
System.out.print("x");
}
System.out.print("\ndo-while: ");
int j = 3;
do
{
System.out.print("x");
}while (--j > 0);
This prints
while: xx
do-while: xxx
A real time example.
There is a contest with 5 level.
In each level if you score 100 you can proceed to next level.
Less code for do while, but not for while.
boolean playContest()
{//do while
int level = 1;
int score;
do
{
score = 0;
score = play();
}while(score>99 && level++<6)
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
boolean playContest()
{//while
int level = 1;
int score;
while(level <6)
{
score = 0;
score = play();
if(score < 100)
break;
level++;
}
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
basic difference between while and do-while is do while will be executed at least once.
when do-while is best option?
in case when you want to execute some actions till you meet condition, of course you could achieve same thing by using while but early termination of loop with break, is nasty and ugly solution
When you want to execute the statement inside do for at least once, then you can go for it.
Directly from Docs
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once,
do {
statement(s)
} while (expression);
No, there is no time a do-while loops is the only option, it is used for convenience when you do not want to repeat code.
I saw this keyword for the first time and I was wondering if someone could explain to me what it does.
What is the continue keyword?
How does it work?
When is it used?
continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:
break terminates the loop (jumps to the code below it).
continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next.
This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:
for(int i=0; i < 10; ++i) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This will print out only the odd numbers.
Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.
As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration
Example: This is a code to print the odd numbers from 1 to 10
the compiler will ignore the print code whenever it sees continue moving into the next iteration
for (int i = 0; i < 10; i++) {
if (i%2 == 0) continue;
System.out.println(i+"");
}
As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet will contain odd numbers only 100%... you are wrong!
Continue is a keyword in Java & it is used to skip the current iteration.
Suppose you want to print all odd numbers from 1 to 100
public class Main {
public static void main(String args[]) {
//Program to print all odd numbers from 1 to 100
for(int i=1 ; i<=100 ; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.
Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.
Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '
public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}
}
It will print: aa cc Out of the loop.
If you use break in place of continue(After if.), it will just print aa and out of the loop.
If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
I'm a bit late to the party, but...
It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:
while ((buffer[i++] = readChar()) >= 0)
continue;
In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.
It's a little more obvious than the equivalent:
while (...)
{ }
and definitely better (and safer) coding style than using an empty statement like:
while (...)
;
continue must be inside a loop Otherwise it showsThe error below:
Continue outside the loop