HowToDoInJava

  • All Tutorials
  • Spring Boot
  • Java 8
  • Interview Questions
Home / Core Java / Java Basics / Labeled Statements in Java

Labeled Statements in Java

October 26, 2013 by Lokesh Gupta

Welcome back to my next post in series of less known java features. If you are new to this series, I would like to encourage you to read previously discussed features e.g. usage of sun.misc.Unsafe, SerialVersionUID and related facts, Instanceof operators don’t need explicit null checks and Checked exceptions thrown in initializer blocks can be declared by the constructors etc.

In this post, I will discuss another such feature in java which is labeled blocks. They are logically similar to to goto statements in C/C++.

How many times, we have been told that “goto” statements are evil. I myself have read about this so called evil through many respected authors of our time. But, if you look at the sourcecode of String.java, and read the sourcecode of public String toLowerCase(Locale locale) method, you will something like this:

scan :
            for (firstUpper = 0 ; firstUpper < count; ) {
                char c = value[offset+firstUpper];
                if ((c >= Character.MIN_HIGH_SURROGATE) &&
                    (c <= Character.MAX_HIGH_SURROGATE)) {
                    int supplChar = codePointAt(firstUpper);
                    if (supplChar != Character.toLowerCase(supplChar)) {
                        break scan;
                    }
                    firstUpper += Character.charCount(supplChar);
                } else {
                    if (c != Character.toLowerCase(c)) {
                        break scan;
                    }
                    firstUpper++;
                }
            }
            return this;
        }
What is this “scan:”. This is the labeled block which we are going to learn about today. Well, they always told us not to use them and used it in perhaps most used class in JDK distribution. :)

In java, we all know for what purpose the keywords “break” and “continue” exist. Basically, statements break and continue alter the normal control flow of compound statements. They can be used in two ways:

Default usage: e.g.

while (Some condition) {
  if ( a specific condition ) 
  break;        //Default usage
  else
  normal business goes here..
}

Another way is to use with a label.

hackit:
while (Some condition) {
  if ( a specific condition ) 
  break hackit;       //Usage with label
  else
  normal business goes here..
}

FYI, A label is any valid Java identifier followed by a colon. e.g. outer:, inner:, inner123:, inner_: etc.

Whenever during a program execution, a labeled break statement is encountered that control immediately goes out of enclosing labeled block. Similarly, labeled continue will bring control back to start. Just like in normal break and continue statements, with additional names given to blocks.

Let’s look at more example usages:

outer: for (int i = 0; i < 10; i++) {
  inner: for (int j = 10; j > 0; j--) {
    if (i != j) {
      System.out.println(i);
      break outer;
    }else{
      System.out.println("-->>" + i);
      continue inner;
    }
  }
}

//OR

int a = 10;
int b = 12;

block1: {
    if (a < 0) {
      break block1;
    }
    if (b < 0) {
      break block1;
    }
    System.out.println( a + b );
  }
}

Bullet points

  • Java does not have a general goto statement.
  • The statements break and continue in Java alter the normal control flow of compound statements. They can use labels which are valid java identifiers with a colon.
  • Labeled blocks can only be used with break and continue statements.
  • They must be called within its scope. You can not refer them scope of labeled block.
  • The break statement immediately jumps to the end (and out) of the appropriate compound statement.
  • The continue statement immediately jumps to the next iteration (if any) of the appropriate loop.
  • A continue statement does not apply to a switch statement or a block statement, only to compound statements that loop: for, while, and do.

Happy Learning !!

Stay Updated with Awesome Weekly Newsletter

Unsubscribe

About Lokesh Gupta

Founded HowToDoInJava.com in late 2012. I love computers, programming and solving problems everyday. A family guy with fun loving nature. You can find me on Facebook, Twitter and Google Plus.

Ask Questions & Share Feedback Cancel reply

Your email address will not be published. Required fields are marked *

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Help me fight spammers. Solve this simple math. *

Search Tutorials

  • Email
  • Facebook
  • RSS
  • Twitter

Recommended

  • 10 Life Lessons
  • How to Start New Blog
  • Secure Hash Algorithms
  • Regular Expressions
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices
  • Java Interview Questions
  • Microservices Tutorial
  • REST API Tutorial

Java Tutorial

  • Java – Introduction
  • Java – ClassPath
  • Java – Create Class
  • Java – main() Method
  • Java – Static Keyword
  • Java – Continue Keyword
  • Java – Break Keyword
  • Java – Transient Keyword
  • Java – Static Import
  • Java – Do-while Loop
  • Java – While Loop
  • Java – For Loop
  • Java – Enhanced Foreach Loop
  • Java – Types of Statements
  • Java – Switch Statement
  • Java – If-else Statement
  • Java – Labeled Statement
  • Java – Operators
  • Java – Data Types
  • Java – Primitive Types
  • Java – System Properties
  • Java – 32-bit vs. 64-bit
  • Java – hashCode() and equals()
  • Java – java.exe vs javaw.exe
  • Java – Generate Bytecode
  • Java – Little-Endian vs Big-Endian
  • Java – Wrapper Classes Internal Caching
  • Pass-by-Value vs. Pass-by-Reference
  • Correct way to compare floats


Developer Tools

  • JSON Formatter and Minifier
  • XML Formatter and Minifier
  • CSS Formatter and Minifier
  • HTML Formatter and Minifier

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

References

  • Java 8 API
  • Spring Framework Reference
  • RESTEasy Reference
  • Hibernate User Guide
  • Junit Wiki
  • Maven FAQs

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. Site hosted on Bluehost

.