BIG
DATA

JAVA

CONTROL FLOW STATEMENTS IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Generally the statements inside your java code are executed from top to bottom, in the order that they appear. Control flow statements, change or break the flow of execution by implementing decision making, looping, and branching your program to execute particular blocks of code based on the conditions.

There are 3 types of control flow statements supported by the Java programming language.

  • Decision-making statements : if-then, if-then-else, switch
  • Looping statements : for, while, do-while
  • Branching statements : break, continue, return

Java if statements

The if-then Statement

The if-then statement is the most basic of all the control flow statements. It enables your program to execute a certain section of code depending on the state of variables, or values returned from methods.

if(isCar)
{
	System.out.println("I am a Car");
}

If isCar test evaluates to false, control jumps to the end of the if-then statement. In Java, the opening and closing braces are optional.But this is applicable only if the block of code to be executed is just a single statement:

if(isCar)
	System.out.println("I am a Car");

But as a good practice, it is advisable to put the brackets around the statements, even if there is only one statement to execute.This is because, in the begining you may start with one statement and later during the development phase you may add more statements. During this a common mistake would be forgetting to add the newly required braces which compiler cannot catch.

The if-then-else Statement

The if-then-else statement provides a alternate path of execution when an "if" clause evaluates to false.

if(isCar)
{
	System.out.println("I am a Car");
}
else
{
	System.out.println("I am a Truck");
}
Chaining if Statements

You can chain if-else statements, and create a decision tree sort of thing.

if(vehicle="Car")
{
	System.out.println("I am a Car");
}
else if(vehicle="Truck")
{
	System.out.println("I am a Truck");
}
else
{
	System.out.println("I am a Bike");
}

In some other example, there could be a chance that it can satisfy more than one expression in the statements. But in Java, once a condition is satisfied and appropriate statements are executed then the remaining conditions are skipped.

Switch statement

Another way to control the flow of your programs with decision-making statements is by a switch statement. A switch statement gives you the option to test for a range of values for your variables. If you think your if-else-if statements is long and complex, you can use switch statement instead.

class SwitchDemo {
    public static void main(String[] args) {
        int age = 3;
        String yourAge;
        switch (age) {
            case 1:  System.out.println("You are one yr old");
                     break;
            case 2:  System.out.println("You are two yr old");
                     break;
            case 3:  System.out.println("You are three yr old");
                     break;
            default: System.out.println("You are more than three yr old");
                     break;
        }
    }
}

The body of a switch statement is known as a switch block. The switch statement evaluates its expression within the brackets, then executes all statements that follow the matching case label. Again there might be more than one cases being matched but switch will choose the first immidiate matching case ignoring the others.

break statement is necessary.Because without it, statements in switch blocks fall through. Lets take a look at below program:

class SwitchDemo {
    public static void main(String[] args) {
        int age = 2;
        String yourAge;
        switch (age) {
            case 1:  System.out.println("You are one yr old");
            case 2:  System.out.println("You are two yr old");
            case 3:  System.out.println("You are three yr old");
            default: System.out.println("You are more than three yr old");
				break;
        }
    }
}

Output will be:

You are two yr old
You are three yr old
You are more than three yr old

If you notice the output, all statementsafter matching case label(in our example case 2) are executed in sequence until a break statement if found.Though technically, the final break is not required because execution flow falls out of the switch statement. You can use this feature for some other situation like this:

class SwitchDemo {
	public static void main(String[] args) {
		int age = 2;
		String yourAge;
		switch (age) {
			case 1:
			case 2:
			case 3: System.out.println("You are three or less than three yr old");
				break;
			case 4: 
			case 5: 
			case 6: System.out.println("You are six or less than six yr old");
				break;
			default: System.out.println("You are more than six yr old");
				break;
		}
	}
}

Java While statements

The while loop executes a set of statements while a certain conditions is true. In Java there are 2 variations of while loop: while and do-while loop. Here is a simple while loop example:

int counter = 0;
while(counter < 5) {
    System.out.println("Inside the while loop, counting: " + counter);
    counter++;
}

This above while loop checks whether counter value is less than 5 to check if the statements inside while loop should be executed or not. If the counter value is less than 5, the while loop body is executed one more time else execution continues at the next statement after the while loop.

You can implement an infinite loop using the while statement, like below:

while (true){
    // some java statements
}

The other type of while loop is the do while loop. Here is the example:

int counter = 0;
do {
    System.out.println("Inside the while loop, counting: " + counter);
    counter++;
} while(counter < 5)

Notice the condition check is moved to end of while body in do-while construct. Which means statements inside the do while loop body is always executed at least once, and is then executed repeatedly while the while loop condition is true.

This is the main difference between java while and do while loop, that the statements inside the do while loop is always executed at least once before the while loop condition is tested.

Java For statements

The Java for loop repeats the execution of a set of Java statements. A for loop executes a block of code as long as some condition is true.

for (initialization; termination condition; increment/decrement) {
    //java statement(s)
}

The initialization expression initializes the loop and is executed only once at the begining when the loop begins. The termination condition is evaluated every loop and if it evaluates to false, the loop is terminated. And lastly increment/decrement expression is executed after each iteration through the loop

Lets print the numbers 1 through 5 to console output.

for(int i=1; i<=5; i++){
	  System.out.println("Printing using for loop. Count is: " + i);
 }

Output will be:

Printing using for loop. Count is: 1
Printing using for loop. Count is: 2
Printing using for loop. Count is: 3
Printing using for loop. Count is: 4
Printing using for loop. Count is: 5

You can create an infinte loop using for loop also:

for(; ; ){
	//java statement(s)
 }

There is another version of for loop in java, which is sometimes referred to as the enhanced for statement. This can be used to make your loops more compact and easy to read. It is generally used to iterate through Collections and arrays.

String[] people = {"Vivek","Kavya","Aryan"};
for (String person : people) {
	System.out.println("Hi, I am " + person);
}

Branching statements

The break Statement

The break statement comes in two forms: labeled and unlabeled. Unlabeled is the most commonly used one in java. You would have already seen break statement in switch case. Similarly you can use unlabeled break to terminate a for, while, or do-while loop.

for(int i=1; i<=5; i++){
	if(i==3)
	{
		System.out.println("Breaking the for loop.");
		break;
	}
	System.out.println("Printing using for loop. Count is: " + i);
}

Output will be:

Printing using for loop. Count is: 1
Printing using for loop. Count is: 2
Breaking the for loop.

Similarly you can use it in while loop also

int counter = 0;
while(counter < 5) {
	if(counter==3)
	{
		System.out.println("Breaking the for loop.");
		break;
	}
    System.out.println("Inside the while loop, counting: " + counter);
    counter++;
}

Remember an unlabeled break statement terminates the innermost switch, for, while, or do-while statement.

The continue Statement

The continue statement skips the current iteration of a for, while , or do-while loop. Continue statement is just similar to the break statement in a way that a break statement is used to pass program control immediately after the end of a loop and the continue statement is used to force program control back to the top of a loop. Meaning it skips one execution of a loop’s body.

while (someCondition) {
    if (someOtherCondition) {
        continue;
    }
    // Do something
}

works the same as below:

while (someCondition) {
    if (!someOtherCondition) {
        // Do something
    }
}

Lets take an example:

int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < nums.length; i++) {
	if (nums[i] % 2 != 0) {
		continue;
	}
	System.out.println(nums[i] + " is even");
}

In the above code we check for even numbers, if it is not then we skip that present loop by using Continue. So the output will be:

0 is even
2 is even
4 is even
6 is even
8 is even
The return Statement

This is the most commonly used branching statement of all. The return statement exits the control flow from the current method, and returns to where the method was invoked. The return Statement can return a value or may not retuen a value. To return a value, just put the value after the return keyword.

But remember data type of the returned value must match the type of the method's declared return value. And so when a method is declared void, use return without a return value.

return count;
return personName;
return;
Nested Loops and Labels

Looping structures can be nested. By default, a break or continue statement affects the innermost loop in which it is located. You can apply an optional label to a looping structure. The label is an identifier followed by a : placed before the looping structure.

Both the break and the continue statement accept an optional label argument. In that case, the break or continue statement affects the looping structure with that label.

Lets take the above continue example and modify it to add labels. As you can see its the same code we used earlier but added a label called GURU.

int[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
GURU:
for (int i = 0; i < nums.length; i++) {
	if (nums[i] % 2 != 0) {
		continue GURU;
	}
	System.out.println(nums[i] + " is even");
}

The output will be same as in continue code. Adding labels is usefull when there are nested loops, like below:

public void searchForNumber() {
	int[][] nums = { {1, 3, 7, 5},
					 {5, 8, 4, 6},
					 {7, 4, 2, 9} };
	int search = 8;
	GURU:
	for (int i = 0; i < nums.length; i++) {
		for (int j = 0; j < nums[i].length; j++) {
			if (nums[i][j] == search) {
				System.out.println(
					"Found " + search + " at position " + i + "," + j);
				break GURU;
			}
		}
	}
}

In the above, label GURU is defined outside the nested loop. So when program encounters break GURU;, it breaks out of nested loop not just inner loop. Hence the below ouput:

Found 8 at position 1,1

Note:When you are decalring a label, you should declare it right before the start of loop syntax. If you declare anywhere else it will throw syntax error.