The Java search: "block" - java

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

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;
}
}
}

How braces affect code output

While I am implementing Selection sort method and executing it, some of elements are sorted while other are not. I checked over the internet about a correct implementation but I didn't find any difference except an extra opening and closing braces.
Here is my code:
public void selectionSort()
{
for(int i = 0;i<=arrSize;i++)
{
int min = i ;
for(int j = i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
}
}
}
And here is what I found on the internet:
public void SelectionSort()
{
for(int i = 0;i<=arrSize;i++)
{
int min = i ;
for(int j=i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
}
}
}
I have tried to track where the error is but I failed so I decided to ask here about this logical error, I hope you to answer the question and explain how braces can affect the output of code in this particular case.
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
and this
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
are two different codes.
in first code you swap elements EVERYTIME
in second code you swap elements only if the if statment is true.
The braces limit the if condition actions. With no baces after the if condition, only one expression will be run conditionally and the swap in the second line after the if will always be executed.
Search more info about the scope of if else expressions limited in Java by braces.
i am trying to learn java myself
You should really get a book about java basics and read though it.
i didn't find any difference except an extra opening and closing braces.
But they make the difference:
Without the braces: if the condition in the if statement is not matched the if skips the next statement only.
In Java the curly braces create so called blocks. In conjuncton with the if statement such a block as a hole is the next statement.
If there are no brackets then the compiler adds internally a bracket only for the next line. So,
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
is similar to
if(theArray[j]<theArray[min])
{
min = j;
}
swap(min,i);
That's why you are getting the wrong output.
See
for(int j = i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
min = j;
swap(min,i);
}
Above will execute swap method in every iteration of for loop. Because its in for loop block.
And,
for(int j=i+1;j<=arrSize;j++)
{
if(theArray[j]<theArray[min])
{
min = j ;
swap(min,i);
}
}
Above will execute swap method only when if condition satisfied.
Loops, if or any block will consider statements inside braces. If you don't use braces then it will consider only next single statement in block.

break with label not bringing control to label

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

How do I break from the main/outer loop in a double/nested loop? [duplicate]

This question already has answers here:
How do I break out of nested loops in Java?
(37 answers)
Closed 6 years ago.
If I have loop in a loop and once an if statement is satisfied I want to break main loop, how am I supposed to do that?
This is my code:
for (int d = 0; d < amountOfNeighbors; d++) {
for (int c = 0; c < myArray.size(); c++) {
if (graph.isEdge(listOfNeighbors.get(d), c)) {
if (keyFromValue(c).equals(goalWord)) { // Once this is true I want to break main loop.
System.out.println("We got to GOAL! It is "+ keyFromValue(c));
break; // This breaks the second loop, not the main one.
}
}
}
}
Using a labeled break:
mainloop:
for(){
for(){
if (some condition){
break mainloop;
}
}
}
Also See
“loop:” in Java code. What is this, and why does it compile?
Documentation
You can add labels to your loop, and use that labelled break to break out of the appropriate loop: -
outer: for (...) {
inner: for(...) {
if (someCondition) {
break outer;
}
}
}
See these links for more information:
Branching Statements
JLS - Break Statement
You can just return the control from that function. Or use the ugly break labels approach :)
If there is another code parts after your for statement, you can refactor the loops in a function.
IMO, the use of breaks and continue should be discouraged in OOP, since they affect the readability and the maintenance. Sure, there are cases where they are handy, but in general I think that we should avoid them, since they will encourage the use of goto style programing.
Apparently variations to this questions are posted a lot. Here Peter provided some good and odd uses using labels.
It looks like for Java a labeled break appears to be the way to go (based on the consensus of the other answers).
But for many (most?) other languages, or if you want to avoid any goto like control flow, you need to set a flag:
bool breakMainLoop = false;
for(){
for(){
if (some condition){
breakMainLoop = true;
break;
}
}
if (breakMainLoop) break;
}
Just for fun:
for(int d = 0; d < amountOfNeighbors; d++){
for(int c = 0; c < myArray.size(); c++){
...
d = amountOfNeighbors;
break;
...
}
// No code here
}
Comment on break label : it's a forward goto. It can break any statement and jump to the next:
foo: // Label the next statement (the block)
{
code ...
break foo; // goto [1]
code ...
}
//[1]
The best and easy methods for beginners even:
outerloop:
for(int i=0; i<10; i++){
// Here we can break the outer loop by:
break outerloop;
innerloop:
for(int i=0; i<10; i++){
// Here we can break innerloop by:
break innerloop;
}
}

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;
}
}
}

Categories

Resources