break with label not bringing control to label - java

I am new to Java and preparing for OCA. I was experimenting with break and continue with label. By description in guide book it seemed both when with label, just bring the control to the label. But using test code neither it is throwing error when label for break is as earlier line nor starting the execution from label.
Though I am never going to use break and continue with label. But it important to understand it from exam point of view.
Sample code:
public class B{
public static void main(String[] args){
int i = 0;
label1: for(;i<=10;i++){
System.out.println(i);
if(i==4)
continue label1;
}
System.out.println("out" + i);
i=0;
label2: for(;i<=10;i++){
System.out.println(i);
if(i==4)
break label2;
}
System.out.println("out" + i);
}
}
Result:
java B
0
1
2
3
4
5
6
7
8
9
10
out11
0
1
2
3
4
out4
Why break is not continuing execution from label?
Also including excerpt from the guide book:
excerpt
My understanding from example in Yassir's answer:
label should have a block to follow.
continue brings control at the start of the block and break brings at the end. Thanks

There is a difference between both statements.
Break (JLS §14.15)
A break statement transfers control out of an enclosing statement.
Continue (JLS §14.16)
[...] Control passes to the loop-continuation point of an iteration
statement.
Example
The following are two very simple example, not useful at all in real life, just to demonstrate the actions using different statements.
// This will print "continue" forever.
CONTINUE_LOOP:
while(true) {
System.out.println("continue");
continue CONTINUE_LOOP;
}
// This will only print "break" once and then break out of the loop
BREAK_LOOP:
while(true) {
System.out.println("break");
break BREAK_LOOP;
}

Break needs simple or nested loops. Your example is having single loop so not able to feel effect. Your example can be modified to demonstrate power of break as follows (not using any for, while loop, need if to avoid code unreachable error):
public class B{
public static void main(String[] args){
int i = 0;
label1:
{
label2:
{
i++;
if(i>0)
break label1;
i++;
}
i++;
}
System.out.println("out" + i);
}
}
The code will print out 1 but if you change if condition to i==0 or i<1 then you will get 3 as answer. If you change break statement to break label2 then you will get 2 as answer.
In case of continue you need label to be a loop label.
Hope it helps you in passing OCA exam.

The break with label will cause the program to continue execution AFTER the label whereas the continue with label will cause the program to continue execution FROM the label. This is because break is for "breaking out" of a loop or label where as continue is for "continuing" execution within a loop or label but at the next loop iteration.
The following break with label example uses 3 loops, all nested within each other. Since there’s no way to completely break out of the outer most loop from inside the inner most loop, we can use the label outer1 to accomplish this and specify the label next to the break statement.
outer1:
for(int i=0; i<5; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<2; k++) {
System.out.println("[" + i + "][" + j + "][" + k + "]");
if(j == 3) {
break outer1;
}
}
}
}
Output:
[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0]
Notice how the last line displayed is “[0][3][0]” which is where j == 3 and that’s where we called break outer1; to break out of the outer most loop.
You can also use labels with the continue statement to continue looping from a specific point. Taking the last example and just changing one line to specify continue outer1; instead of break outer1; will cause the loop to continue looping from the outer1 label instead of breaking out of the loop. Note how each time continue outer1 is called, the code continues from the outer loop after incrementing the loop index i by 1.
outer1:
for(int i=0; i<5; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<2; k++) {
System.out.println("[" + i + "][" + j + "][" + k + "]");
if(j == 3) {
continue outer1;
}
}
}
Output:
[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[1][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[1][0][1]
[1][1][0]
[1][1][1]
[1][2][0]
[1][2][1]
[1][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[2][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[2][0][1]
[2][1][0]
[2][1][1]
[2][2][0]
[2][2][1]
[2][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[3][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[3][0][1]
[3][1][0]
[3][1][1]
[3][2][0]
[3][2][1]
[3][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[4][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[4][0][1]
[4][1][0]
[4][1][1]
[4][2][0]
[4][2][1]
[4][3][0]
Source: Loops in Java – Ultimate Guide

Related

how do I break the outermost for-loop in a switch in a nested for-loop? [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 11 months ago.
I have two for loops and in the innermost for loop I have a switch. And is it possible that in one case of the switch, the entire trip through the outermost loop should be aborted, so that one goes over to the next value automatically, for example, the outermost loop is at the 1 pass and with the command in the switch, I come to the second pass, is that possible?
With break it will not work, do you have any ideas?
example:
for (){
for (){
switch(){
case 1:
//now I want to break here the inner loop, to go 1 step further, by the outer loop
}
}
// do something not wanted in case 1
}
As I am not certain exactly what you consider first I labelled both. The following will continue the next iteration of the outer loop.
outer:
for () {
inner:
for () {
switch() {
case 1:
continue outer; // or break inner;
}
}
}
Note that the in the case of break inner;, the label must be still be included since break; would simply break out of the switch block.
you can use label:
first :for (int i = 0; i < args.length; i++) {
second : for (int j = 0; j < args.length; j++) {
switch (j) {
case 1:
break second;// use this for breaking the second loop or use
//continue first; // to break the second and continue the first
default:
break;
}
}
}

Why is the statement unreachable?

int i = 0, j = 5;
tp: for (;;) {
i++;
for (;;) {
if(i > --j) {
break tp;
}
}
System.out.println("i =" + i + ", j = " + j); //Unreachable statement, why?
}
I thought the statement is reachable because there is the break statement before, therefore the statement followed by System.out.println can complete normally, since System.out.println is reachable. Where is the mistake?
Because you have two infinite loops. Change
break tp;
To
break;
And that statement is reachable.
Your break statement brings to back to the start of the outer loop (tp label). That's why you can never reach the println statement.
The inner loop is infinite. If there were nothing inside it, it should be clear that the print is unreachable. If you add a break tp inside it it will break the enclosing loop not the inner one, so the statement remains unreachable.
Either use break to break the inner loop or label the inner loop with tp to correct it.
your code is like
L1 : INFINITE LOOP
{
L2 : INFINITE LOOP
{
break to return to L1
}
SOP("SOmething")
}
So whenever the loop L2 breaks, it takes control back to loop L1 and again the loop L2 starts.
This will continue forever and the control will never be able to exit loop L2 and reach SOP statement, thus SOP statement is unreachable.

The Java search: "block"

Has anyone ever seen the following in Java?
public void methodName(){
search:
for(Type[] t : Type[] to){
do something...
}
}
Can someone point me to documentation on the use of "search:" in this context? Searching for "search:" has not been productive.
Thanks
It's a label. From §14.7 of the Java Language specification:
Statements may have label prefixes...
(Boring grammar omitted, pain to mark up)
Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.
One place you frequently see labels is in nested loops, where you may want to break out of both loops early:
void foo() {
int i, j;
outerLoop: // <== label
for (i = 0; i < 100; ++i) {
innerLoop: // <== another label
for (j = 0; j < 100; ++j) {
if (/*...someCondition...*/) {
break outerLoop; // <== use the label
}
}
}
}
Normally that break in the inner loop would break just the inner loop, but not the outer one. But because it's a directed break using a label, it breaks the outer loop.
This is an example of a labelled loop.
It allows you to break or continue the target loop instead of your current loop.
Outer:
for(int intOuter=0; intOuter < intArray.length ; intOuter++)
{
Inner:
for(int intInner=0; intInner < intArray[intOuter].length; intInner++)
{
if(intArray[intOuter][intInner] == 30)
{
blnFound = true;
break Outer; // this line breaks the outer loop instead of the inner loop.
}
}
}
example taken from : http://www.java-examples.com/java-break-statement-label-example
It is a Java label as defined here in JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#78994

Please explain the usage of Labeled Statements

Is breaking and continuing the only uses of labeled statements in Java?
When have you used Labeled Statements in your programs?
Sorry the code snippet has been deleted. I am splitting the question
JLS 14.7 Labeled statements
(edited for clarity)
Statements may have label prefixes (Identifier : Statement). The Identifier is declared to be the label of the immediately contained Statement.
Unlike C and C++, the Java programming language has no goto statement; identifier statement labels are used with break (§14.15) or continue (§14.16) statements appearing anywhere within the labeled statement.
So the JLS is clear that labels are used with break or continue, and no other grammatical element of the Java programming language uses it.
Strictly speaking, break and continue, labeled or not, are NEVER necessary. They can always be written out of the code. Used idiomatically, however, they can lead to more readable code.
Here's an illustrative example: given an int[], we want to :
print "One (1)" on 1
print "Two (2)" on 2
print "Zero " on 0
immediately stop processing on any other number
int[] arr = { 1, 2, 0, 1, -1, 0, 2 };
loop:
for (int num : arr) {
switch (num) {
case 1:
System.out.print("One ");
break;
case 2:
System.out.print("Two ");
break;
case 0:
System.out.print("Zero ");
continue loop;
default:
break loop;
}
System.out.print("(" + num + ") ");
}
// prints "One (1) Two (2) Zero One (1) "
Here we see that:
The different numbers are processed in a switch
Unlabeled break in the switch is used to avoid "fall-through" between cases
Labeled continue loop; is used to skip post-processing on case 0: (the label is not necessary here)
Labeled break loop; is used to terminate the loop on default: (the label is necessary here; otherwise it's a switch break)
So labeled break/continue can also be used outside of nested loops; it can be used when a switch is nested inside a loop. More generally, it's used when there are potentially multiple break/continue target, and you want to choose one that is not immediately enclosing the break/continue statement.
Here's another example:
morningRoutine: {
phase1: eatBreakfast();
if (grumpy) break morningRoutine;
phase2: kissWife();
phase3: hugChildren();
}
http://stackoverflow.com is the best website ever!
Here's another case of a labeled break being used not within an iterative statement, but rather within a simple block statement. One may argue that the labels lead to better readability; this point is subjective.
And no, the last line DOES NOT give compile time error. It's actually inspired by Java Puzzlers Puzzle 22: Dupe of URL. Unfortunately, the puzzle does not go into "proper" use of labeled statements in more depth.
Yes, break and continue are the only two uses for labeled statements in Java. (Java has no goto statement.)
You can use a label to break out of nested loops.
outer:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // Never prints
}
System.out.println("Good-Bye");
When you continue back to the outer label, you're skipping the remainder of both the inner and the outer loop, including the print statement.
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;
}
}
}

What is the "continue" keyword and how does it work in Java?

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

Categories

Resources