Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Casting
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Operators
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays
Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance
Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Polymorphism
Introduction
Interfaces
Packages
Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions


Branching Statements

We will now look at the last set of control statements in Java- branching statements. They are used to transfer control to another point in the code. Java's branching statements are defined by the three keywords- break, continue and return. The break and continue statements have two forms: the labelled form and the unlabelled form. We shall now look at each one of them in detail.

Java's break statement is used to exit out of a loop. We have already seen the use of the break statement in the switch structure. We shall now see their use in loops. break is normally executed as a target of a decision making statement like if. Look at the following for loop which should actually print the integers from one to seven. However, because of the break statement that is associated with an if, only the numbers up to four are printed. When the break keyword is encountered, controls gets transferred to the end of the loop and statements following the loop are executed.

        for (int i = 1; i <= 7; i++) {
            System.out.println(i);
            if (i == 4) {
                break;
            }
        }

The above code will print the numbers from 1 to 4, one each one line.

1
2
3
4

When loops are nested within one another, the use of break will causes control to move out of the loop to which the break statement belongs. Look at the following partial code which contains three loops nested within one another. The break statement is a part of the second for loop. On encountering it, control shifts to the line indicated by "// control shifts here".

for ( ..... ) {
    for ( ..... ) {
        for ( ..... ) {
        }
        if ( ..... ) {
            break;
        }
    }
    // control shifts here
}

In the above program, if on encountering the break statement, we want control to be transferred to the end of the outermost loop instead of the second loop to which the break statement is associated by default, we use a labelled break statement. Before using it, we need to define a label. A label is an identifier followed by a colon. A label is associated to the loop that is defined immediately after the label. When the break is followed by a label, encountering it will cause the control to be shifted to the exit of the loop corresponding to that particular label. Look at the first statement where a label named "here" (Label names should follow the rules of identifiers), is set to be associated with the outer for loop. When the break statement is encountered in the for loop, control is transferred to the end of the outer loop instead of the inner loop as a labelled break has been used.

here:
for ( ..... ) {
    for ( ..... ) {
        if ( ..... ) {
            break here;
        }
    }
// control shifts here on encountering the labelled break

You will be able to appreciate the use of these branching statements when we deal with arrays. However, for the time being, to help you get familiar with the two forms of break statement's, we present below an example, with has three for loops nested within one another. We also have a label for each of these for loops. The code is first executed without any break or continue statements and then, we introduce several break statements, labelled and unlabelled and show you the outputs.

public class Break Example {

    public static void main(String[] args) {
        label1:
        for (int i = 1; i <= 3; i++) {
            label2:
            for (int j = 1; j <= 3; j++) {
                label3:
                for (int k = 1; k <= 3; k++) {
                    System.out.print(k);
                // line1
                }
                System.out.println();
            //line2
            }
            System.out.println();
        //line3
        }
    }
}

And here is a table. Use it to manipulate the above code by replacing line1, line2 and line3 with the contents of this table. Run your program and match your results with the ones shown here. Reason out for yourself the logic behind the output. Note that in this example, we haven't executed break statements as a target of a decision making statement to make the code simpler.

In certain rows of the above table, we have stated //compilation errors. The code in those cases is incorrect since we are trying to access labels that are not known in those scopes. For example, when two loops are nester within one another with the outer loop labelled outer: and the inner loop labelled inner:. Trying to break to inner within the body of the outer loop will result in a compilation error.

outer:
for ( ..... ) {
    inner:
    for ( ..... ) {
    }
    break inner; // error
}

You can try out more combinations for the three lines in the above program by including the break statements on more than a single line. For your reference, 54 combinations are possible in all, including the above stated ones. A majority of these would result in compilation errors.

Now we move on to the continue statement. The continue statement just like the break statement has two forms. When the continue statement is encountered, the remainder of the loop in the current iteration is skipped and control passes to the condition of the loops in while and do while loops while in a for loop, control get transferred to the increment/ decrement part. Given below is a program that prints only positive integers from 1 to 10 using a for loop and the continue statement. The program would of course be much simpler without the use of continue statement but the purpose of this program is to help you learn the working of the continue statement rather than code a program to print even numbers.

        for (int i = 1; i <= 10; i++) {
            if (i % 2 != 0) {
                continue;
            }
            System.out.println(i);
        }

Just like the labelled break statement, we also have the labelled continue statement and this functions in a similar way. Control gets transferred to the corresponding condition (in case of while and do while) or the increment/ decrement operation (in case of a for loop) that that belongs to the stated label.

Just like the table above for the break statement, we present below a table for the continue statement.

Note that the first three sets have the same output. This is because in each of the cases, whether or not the continue statement is used, the flow of control is the same.

The last among Java's branching statements is the return statement. As we already know, the return statement is used in methods to optionally return a value and transfer control back to the calling method. To make it more simple and clear, the return statement skips the remaining of the method. Look at the following code for example:

public class ReturnExample {

    public static void main(String[] args) {
        meth(true);
        System.out.println("end of main");
    }

    public static void meth(boolean b) {
        System.out.println("line1");
        if (b) {
            return;
        }
        System.out.println("line2");
        System.out.println("line3");
    }
}

The output of this program would be:

line1
end of main

When meth() is invoked with a true argument, the return statement is executed. This statement causes the remaining statements in the method to be skipped and control transfers back to the calling method. The return statement works in a similar manner when used with methods except that a value to be returned should also be specified.

As we have already learnt, unreachable code in Java generates compilation errors. For example any code written after the return statement in a method containing a single return statement is an unreachable statement. We have already seen this when dealing with get and set methods. And at that time, you have been promised that you will be shown an example where such a usage is allowed when decision making statements are used. The above program is such an example. The statements that print line2 and line3 are not classified as unreachable even though they will never be executed in this particular program. This is because they may be executed when meth() is called with a false argument in another program. Hence, the statements are not unreachable.

This is all that we have about control structures in Java. We will now move to arrays in which the for loop is widely employed.

Privacy Policy