Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Core Java Basics. 2 Comments on Control statements in Java

In this article you will learn about the control statements in Java. We will look at what are control statements, types of control statements and some example programs which demonstrate the use of control statements in Java.

 

What are control statements?

 

In a Java program, we already know that execution starts at main method. The first statement inside the body of main method is executed and then the next statement and so on. In general, the statements execute one after another in a linear fashion.

 

What if we want the statements to execute in a non-linear fashion i.e., skip some statements or repeat a set of statements or select one set of statements among several alternatives based on the outcome of evaluating an expression or the value of a variable?

 

To solve the above mentioned problems, every programming language provides control statements which allow the programmers to execute the code in a non-linear fashion.

 

Types or categories of control statements in Java

 

In Java, control statements can be categorized into the following categories:

  1. Selection statements (if, switch)
  2. Iteration statements (while, do-while, for, for-each)
  3. Jump statements (break, continue, return)

 

Selection statements

 

As the name implies, selection statements in Java executes a set of statements based on the value of an expression or value of a variable. A programmer can write several blocks of code and based on the condition or expression, one block can be executed.

 

Selection statements are also known as conditional statements or branching statements. Selection statements provided by Java are if and switch.

 

if statement

 

The if statement is used to execute a set of statements based on the boolean value returned by an expression. Syntax of if statement is as shown below:

if(condition/expression)
{
	statements;
}

 

If you want to execute only one statement in the if block, you can omit the braces and write it as shown below:

if(condition/expression)
	statement;

 

In the above syntax, the set of statements are executed only when the condition or expression evaluates to true. Otherwise, the statement after the if block is executed.

 

Let’s consider the following example which demonstrates the use of if statement:

int a = 10;
if(a < 10)
	System.out.println(“a is less than 10”);

 

The output for the above piece of code will be a blank screen i.e. no output because the condition a < 10 returns false and the print statement will not be executed.

 

In the above piece of code, instead of displaying nothing when the condition returns false, we can show an appropriate message. This can be done using the else statement.

 

Remember that you can’t use else without using if statement. By using the else statement our previous example now becomes as follows:

int a = 10;
if(a < 10)
	System.out.println(“a is less than 10”);
else
	System.out.println(“a is greater than or equal to 10”);

 

Nested if statement

 

If you want to test for another condition after the initial condition available in the if statement, it is common sense to write another if statement. Such nesting of one if statement inside another if statement is called a nested if statement. Syntax of nested if statement is as shown below:

if(condition)
{
	if(condition)
	{
		if(condition)
		{
			…
		}
	}
}

 

We can also combine multiple conditions into a single expression using the logical operators. As an example for nested if, let’s look at a program for finding the largest of the three numbers a, b and c. Below we will look at a code fragment which shows logic for finding whether a is the greatest or not:

if(a > b)
{
	if(a > c)
	{
		System.out.println(“a is the largest number”);
	}
}

 

As mentioned above we can convert a nested if into a simple if by combining multiple condition into a single condition by using the logical operators as shown below:

if(a > b && a > c)
{
	System.out.println(“a is the largest number”);
}

 

if-else-if Ladder

 

The if-else-if ladder is a multi-way decision making statement. If you want to execute one code segment among a set of code segments, based on a condition, you  can use the if-else-if ladder. The syntax is as shown below:

if(condition)
{
	Statements;
}
else if(condition)
{
	Statements;
}
else if(condition)
{
	Statements;
}
…
else
{
	Statements;
}

 

Looking at the above syntax, you can say that only one of the blocks execute based on the condition. When all conditions fail, the else block will be executed. As an example for if-else-if ladder, let’s look at a program for finding whether the given character is a vowel (a, e, i, o, u) or not:

char ch;
ch = ‘e’;   //You can also read input from the user
if(ch == ‘a’)
{
	System.out.println(“Entered character is a vowel”);
}
else if(ch==’e’)
{
	System.out.println(“Entered character is a vowel”);
}
else if(ch==’i')
{
	System.out.println(“Entered character is a vowel”);
}
else if(ch==’o’)
{
	System.out.println(“Entered character is a vowel”);
}
else if(ch==’u’)
{
	System.out.println(“Entered character is a vowel”);
}
else
{
	System.out.println(“Entered character is not a vowel”);
}

 

In the above program, the else block serves as a default block that is to be executed in case if the entered character is not a, e, i, o or u.

 

switch Statement

 

The switch statement is another multi-way decision making statement. You can consider the switch as an alternative for if-else-if ladder. Every code segment written using a switch statement can be converted into an if-else-if ladder equivalent.

 

Use switch statement only when you want a literal or a variable or an expression to be equal to another value. The switch statement is simple than an equivalent if-else-if ladder construct.

 

You cannot use switch to test multiple conditions using logical operators, which can be done in if-else-if ladder construct. Syntax for switch statement is as shown below:

switch(expression)
{
	case label1:
		Statements;
		break;
	case label2:
		Statements;
		break;
	case label3:
		Statements;
		break;
	…
	default:
		Statements;
		break;
}

 

Some points to remember about switch statement:

  1. The expression in the above syntax can be a byte, short, int, char or an enumeration. From Java 7 onwards, we can also use Strings in a switch
  2. case is a keyword use to specify a block of statements to be executed when the value of the expression matches with the corresponding label
  3. The break statement at the end of each case is optional. If you don’t use break at the end of a case, all the subsequent cases will be executed until a break statement is encountered or the end of the switch statement is encountered.
  4. The default block is also optional. It is used in a switch statement to specify a set of statements that should be executed when none of the labels match with the value of the expression. It is a convention to place the default block at the end of the switch statement but not a rule.

 

As an example for switch statement, let’s consider the vowel’s example discussed above:

char ch;
ch = ‘u’;  //You can also read input from the user
switch(ch)
{
	case ‘a’:
		System.out.println(“Entered character is a vowel”);
		break;
	case ‘e’:
		System.out.println(“Entered character is a vowel”);
		break;
	case ‘i':
		System.out.println(“Entered character is a vowel”);
		break;
	case ‘o’:
		System.out.println(“Entered character is a vowel”);
		break;
	case ‘u’:
		System.out.println(“Entered character is a vowel”);
		break;
	default:
		System.out.println(“Entered character is not a vowel”);
		break;  //There is no need of this break. You can omit this if you want
}

 

Iteration Statements

 

While selection statements are used to select a set of statements based on a condition, iteration statements are used to repeat a set of statements again and again based on a condition for finite or infinite number of times.

 

What is the need for iteration statements or looping statements? To answer this, let’s consider an example. Suppose you want to read three numbers from user. For this you might write three statements for reading input. In another program you want to read ten numbers. For this you write ten statements for reading input. Yet in another program you want to read ten thousand numbers as input. What do you do? Even copying and pasting the statements to read input takes time. To solve this problem, Java provides us with iteration statements.

 

Iteration statements provided by Java are: for, while, do-while and for-each

 

while Statement

 

while is the simplest of all the iteration statements in Java. Syntax of while loop is as shown below:

while(condition)
{
	Statements;
}

 

As long as the condition is true, the statements execute again and again. If the statement to be executed in any loop is only one, you can omit the braces. As the while loop checks the condition at the start of the loop, statements may not execute even once if the condition fails. If you want to execute the body of a loop atleast once, use do-while loop.

 

Let’s see an example for reading 1000 numbers from the user:

int i;
i = 0;
while(i < 1000)
{
	//Code for reading input…
	i++;
}

 

The above loop works in this way. First i is initialized to zero, then condition i < 1000 is evaluated which is true. So the statements for reading input are executed and finally i is incremented by 1 (i++). Again the condition is evaluated and so on. When i value becomes 1000, condition fails and control exits the loop and goes to the next line after the while statement.

 

do-while Statement

 

do-while statement is similar to while loop except that the condition is checked after executing the body of the loop. So, the do-while loop executes the body of the loop atleast once. Syntax of do-while is as shown below:

do
{
    Statements;
}while(condition);

 

This loop is generally used in cases where you want to prompt the user to ask whether he/she would like to continue or not. Then, based on user’s input, the body of the loop will be executed again or else the control quits the loop.

 

Let’s consider an example where the body of the loop will be executed based on the user’s input:

char ch;
do
{
	//Statements;
	System.out.println(“Do you want to continue? Enter Y or N);
	//Statement for reading the character from the user
}while(ch == ‘Y’);

 

In the above code segment, the body of the do-while loop executes again and again as long as the user inputs the character Y when prompted.

 

for Statement

 

The for statement might look busy but provides more control than other looping statements. In a for statement, initialization of the loop control variable, condition and modifying the value of the loop control variable are combined into a single line. The syntax of for statement is as shown below:

for(initialization; condition; iteration)
{
	Statements;
}

 

In the above syntax, the initialization is an assignment expression which initializes the loop control variable and/or other variables. The initialization expression evaluates only once. The condition is a boolean expression. If the condition evaluates to true, the body of the loop is executed. Else, the control quits the loop.

 

Every time after the body executes, the iteration expression is evaluated. Generally, this is an increment or decrement expression which modifies the value of the control variable. All the three parts i.e. initialization, condition and iteration are optional.

 

Let’s consider an example code segment which prints the numbers from 1 to 100:

for(int i = 1; i <= 100; i++)
{
	System.out.println(“i = “ + i );
}

 

In the above code segment, int i = 1 is the initialization expression, i <= 100 is the condition and i++ is the iteration expression.

 

We can create an infinite for loop as shown below:

for( ; ; )
{
	Statements;
}

 

for-each Statement

 

The for-each statement is a variation of the traditional for statement which has been introduced in JDK 5. The for-each statement is also known as enhanced for statement. It is a simplification over the for statement and is generally used when you want to perform a common operation sequentially over a collection of values like an array etc… The syntax of for-each statement is as shown below:

for(type  var : collection)
{
	Statements;
}

 

The data type of var must be same as the data type of the collection. The above syntax is can be read as, for each value in collection, execute the statements. Starting from the first value in the collection, each value is copied into var and the statements are executed. The loop executes until the values in the collection completes.

 

Let’s consider a code segment which declares an array containing 10 values and prints the sum of those 10 values using a for-each statement:

int[ ] array = {1,2,3,4,5,6,7,8,9,10};
int sum = 0;
for(int x : array)
{
	sum += x;
}
System.out.println(“Sum is: “+sum);

 

The equivalent code segment for the above code using a for loop is as shown below:

int[ ] array = {1,2,3,4,5,6,7,8,9,10};
int sum = 0;
for(int x = 0; x < 10; x++)
{
	sum += array[x];
}
System.out.println(“Sum is: “+sum);

 

Which one is better? for or for-each?

 

Nested Loops

 

A loop inside another loop is called as a nested loop. For each iteration of the outer loop the inner loop also iterates. Syntax of a nested loop is shown below:

outer loop
{
	inner loop
	{
		Statements;
	}
}

 

Let’s consider an example which demonstrates a nested loop:

for(int i = 0; i < 5; i++)
{
	for(int j = 0; j <= i; j++)
	{
		System.out.println(“*”);
	}
}

 

Output for the above code segment is:

 

*
**
***
****
*****

 

Jump Statements

 

As the name implies, jump statements are used to alter the sequential flow of the program. Jump statements supported by Java are: break, continue and return.

 

break Statement

 

The break statement has three uses in a program. First use is to terminate a case inside a switch statement, second use to terminate a loop and the third use is,break can be used as a sanitized version of goto which is available in other languages. First use is already explained above. Now we will look at the second and third use of break statement.

 

The break statement is used generally to terminate a loop based on a condition. For example, let’s think that we have written a loop which reads data from a heat sensor continuously. When the heat level reaches to a threshold value, the loop must break and the next line after the loop must execute which might be a statement to raise an alarm. In this case the loop will be infinite as we don’t know when the value from the sensor will match the threshold value. General syntax of the break statement inside a loop is shown below:

Loop
{
	//Statements;
	if(condition)
		break;
	//Statements after break;
}

 

As an example to demonstrate the break statement inside a loop, let’s look at the following code segment:

for(i = 1; i < 10; i++)
{
	System.out.println(i);
	if(i == 5)
		break;
}

 

Output for the above code segment is:

 

1
2
3
4
5

 

When used inside a nested loop, break statement makes the flow of control to quit the inner loop only and not the outer loop too.

 

Another use of the break statement is, it can be used as an alternative to goto statement which is available in other programming languages like C and C++. General syntax of break label statement is as shown below:

label1:
{
	Statements;
	label2:
	{
		Statements;
		if(condition)
			break label1;
	}
	Statements;
}

 

In the above syntax, when the condition becomes true, control transfers from that line to the line which is available after the block labeled label1. This form of break is generally used in nested loops in which the level of nesting is high and you want the control to jump from the inner most loop to the outermost loop. This form of break can be used in all loops or in any other block. Syntax for writing a label is, any valid identifier followed by a colon (:).

 

continue Statement

 

Unlike break statement which terminates the loop, continue statement is used to skip rest of the statements after it for the current iteration and continue with the next iteration. Syntax of continue is as shown below:

Loop
{
	//Statements;
	if(condition)
		continue;
	//Statements after continue;
}

 

Like break statement, continue can also be used inside all loops in Java.

 

As an example to demonstrate the continue statement inside a loop, let’s look at the following code segment:

for(i = 1; i < 5; i++)
{
	if(i == 3)
		continue;
	System.out.println(i);
}

 

Output for the above code segment is:

 

1
2
4
5

 

When the value of i becomes 3, continueis executed and the print statement gets skipped.

 

return Statement

 

The return statement can only be used inside methods which can return control or a value back to the calling method. The return statement can be written at any line inside the body of the method. Common convention is to write the return statement at the end of the method’s body. Let’s consider a small example to demonstrate the use of return statement:

void fact(int n)
{
	if(n == 0) return 1;
	else if(n == 1) return 1;
	else return fact(n)*fact(n-1);
}

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

Hi sir,

Please change the &tl;, >, &amp to , &, in all code examples we can able to see these only.
if(a > b && a > c)
{
System.out.println(“a is the largest number”);
}

Thanks,
Prakash

    Done.

Leave a Reply

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