Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

CONTROL FLOW STATEMENTS

Definition
Control flow statements, however, break up the flow of execution by employing decision
making, looping, and branching, enabling your program to conditionally execute particular blocks
of code.
In Java, program is a set of statements and which are executed sequentially in order in
which they appear. In that statements, some calculation have need of executing with some
conditions and for that a control to that statements has been provided.
In other words, Control statements are used to provide the flow of execution with
condition.

In java program, control structure is divided into three types:


● Selection statement / Decision Making statements
● Iteration statement / looping statements
● Jumps in statement / Branching statements

Selection Statement
Selection statement is also called as Decision-making statements because it provides the
decision-making capabilities to the statements.

Types of Selection flow control statement:


● if statements
● switch statement

 
These two statements are allows the user to control the flow of a program with their conditions.
if statements:
There are various types of if statement in Java.
● if statement
● if-else statement
● if-else-if ladder
● nested if statement

Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}

 
Flow Diagram

Example:
//Java Program to demonstate the use of if statement.
public​ ​class​ IfExample {
public​ ​static​ ​void​ main(String[] args) {
//defining an 'age' variable
​int​ age=20;
//checking the age
​if​(age>18){
System.out.print("Age is greater than 18");
}
}}
Output:
Age is greater than 18
if else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed.

 
Syntax:
if​(condition)
{
//code if condition is true
}
Else
{
//code if condition is false
}
The “if statement” is a commanding decision making statement and is used to manage the flow
of execution of statements.

The “if statement” is the simplest one in decision statements. Above syntax is shows two ways
decision statement and is used in combination with statements.
Following figure shows the “if statement”

Example:1
Program to check whether the number is positive or negative.
import java.util.*;
class NumTest

 
{
public static void main (String[] args)
{
int Result;
Scanner s = new Scanner(System.in);
Result = s.nextInt();
System.out.println("Number is"+Result);
if ( Result < 0 )
System.out.println("The number "+ Result +" is negative");
else
System.out.println("The number "+ Result +" is positive");
}
}

Example:2
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}

 
}
Output:
odd number

Using Ternary Operator


We can also use ternary operator (? :) to perform the task of if...else statement. It is a
shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if
the condition is false, the result of : is returned.
Example:
public​ ​class​ IfElseTernaryExample {
public​ ​static​ ​void​ main(String[] args) {
​int​ number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}
Output:
odd number
Nesting of if-else statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if​(condition1){
//code to be executed if condition1 is true
}​else​ ​if​(condition2){
//code to be executed if condition2 is true
}
else​ ​if​(condition3){

 
//code to be executed if condition3 is true
}
...
else​{
//code to be executed if all the conditions are false
}
If the condition1 is true then it will be goes for condition2. If the condition2 is
true then statement block1 will be executed otherwise statement2 will be executed. If the
condition1 is false then statement block3 will be executed. In both cases the statement4 will
always executed.
Flow Diagram

 
Example:1
Program to find largest number of three given numbers using if else.
class Test
{
public static void main(String args[])
{
int x = 20;
int y = 15;
int z = 30;
if (x > y)
{
 
if (x > z)
System.out.println("Largest number is: "+x);
else
System.out.println("Largest number is: "+z);
}
else
{
if (y > z)
System.out.println("Largest number is: "+y);
else
System.out.println("Largest number is: "+z);
}
}
}

Output:​ Largest number is: 30

Example:2
//Java Program to demonstrate the use of If else-if ladder.
//program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public​ ​class​ IfElseIfExample {
public​ ​static​ ​void​ main(String[] args) {
​int​ marks=65;
​if​(marks<50){
System.out.println("fail"); }
​else​ ​if​(marks>=50 && marks<60){

 
System.out.println("D grade"); }
​else​ ​if​(marks>=60 && marks<70){
System.out.println("C grade"); }
​else​ ​if​(marks>=70 && marks<80){
System.out.println("B grade"); }
​else​ ​if​(marks>=80 && marks<90){
System.out.println("A grade");
}​else​ ​if​(marks>=90 && marks<100){
System.out.println("A+ grade");
}​else​{
System.out.println("Invalid!"); }
}
}
Output:
C grade

Java Nested if statement


The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.

Syntax:
if​(condition){
//code to be executed
​if​(condition){
//code to be executed
}
}

 
Example:
//Java Program to demonstrate the use of Nested If Statement.
public​ ​class​ JavaNestedIfExample {
public​ ​static​ ​void​ main(String[] args) {
//Creating two variables for age and weight
​int​ age=20;
​int​ weight=80;
//applying condition on age and weight
​if​(age>=18){
​if​(weight>50){

 
System.out.println("You are eligible to donate blood");
}
}
}}
Output:
You are eligible to donate blood

Java Switch Statement


The Java ​switch statement​ executes one statement from multiple conditions. It is
like ​if-else-if​ ladder statement. The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can
use ​strings​ in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember
● There can be one or N number of case values for a switch expression.
● The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow ​variables​.
● The case values must be unique. In case of duplicate value, it renders compile-time error.
● The Java switch expression must be of byte, short, int, long (with its Wrapper
type), ​enums​ and string.
● Each case statement can have a break statement which is optional. When control reaches
to the ​break statement​, it jumps the control after the switch expression. If a break
statement is not found, it executes the next case.
● The case value can have a default label which is optional.
Syntax:
switch​(expression){
case​ value1:

 
//code to be executed;
​break​; //optional
case​ value2:
//code to be executed;
​break​; //optional
......
default:
code to be executed ​if​ all cases are not matched;
}
Flow Diagram

Example:1
class Test {
public static void main(String args[]){
char grade;
Scanner s = new Scanner(System.in);
grade = s.next();

 
switch(grade)
{
case ‘S’ : System.out.println(“>90”);
break;
case 'A' : System.out.println(">80 and <=90");
break;
case 'B' :System.out.println(“>70 and <=80”);
break;
case 'C' : System.out.println(“>60 and <=70”);
break;
case 'D' : System.out.println(“>55 and <=60”);
break;
case 'E' : System.out.println(“>50 and <=55”);
break;
case ‘U’: System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Example:2
//Java Program to demonstrate the example of Switch statement
//where we are printing month name for the given number
public​ ​class​ SwitchMonthExample {
public​ ​static​ ​void​ main(String[] args) {
​int​ month=7; //Specifying month number

 
String monthString="";
​switch​(month){
​case​ 1: monthString="1 - January";
​break​;
​case​ 2: monthString="2 - February";
​break​;
​case​ 3: monthString="3 - March";
​break​;
​case​ 4: monthString="4 - April";
......
.....
​default​:System.out.println("Invalid Month!");
}
System.out.println(monthString);
} }
Output: 7 - July

Loop Statements
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. The statements may be executed multiple times
(from zero to infinite number). If a loop executing continuous then it is called as Infinite loop.
Looping is also called as iterations.

 
There are three types of loops in Java.
● while loop
● do-while loop
● for loop
while loop
A while loop statement in java programming language repeatedly executes a target
statement as long as a given condition is true.

Syntax
while(Boolean_expression)
{
//Statements
}
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any non zero value. When executing, if the boolean_expression
result is true, then the actions inside the loop will be executed. This will continue as long as the
expression result is true. When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram:

 
Program
class Test {
public static void main(String args[]) {
int x = 1;
while( x < 10 ){
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

do-while loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do
 
{
//Statements
}while(Boolean_expression);

The Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.

If the Boolean expression is true, the control jumps back up to do statement, and the statements
in the loop execute again.

This process repeats until the Boolean expression is false.

Example
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");

 
}while( x < 20 );
}
}
for loop
for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. A for loop is useful when the user knows how many
times a task is to be repeated.
Syntax
for(initialization; Boolean_expression; update)
{
//Statements
}
● The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. and this step ends with a semi colon (;)
● Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop will not be executed and control jumps to the next
statement past the for loop.
● After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement
can be left blank with a semicolon at the end.
● The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Flow Diagram

 
Example:1
class Loop {
public static void main(String[] args) {

for (int i = 1; i <= 5 ++i) {


System.out.println("Number " + i);
}
}
}

Output:
Number 1
Number 2
Number 3
Number 4
Number 5
Example:2

 
public class Demo {
public static void main(String[] args) {
int num = 10, count, total = 0;

for(count = 1; count <= num; count++){


total = total + count;
}
System.out.println("Sum of first 10 natural numbers is: "+total);
}
}
Output:
Sum of first 10 natural numbers is: 55
Example:3
To print even numbers between the given ranges using for loop.
class EvenNumber
{
public static void main(String args[])
{
int n;
System.out.print("Even number are: ");
for( n = 0; n <= 20; ++n)
{
if (n % 2 == 0)
System.out.print(" "+n);
}
}
}
Jumps in statement
 
Statements or loops perform a set of operations continually until the control variable will
not satisfy the condition. If a user want to break the loop when condition satisfies, then Java give
a permission to jump from one statement to end of loop or beginning of loop as well as jump out
of a loop. “break” keyword use for exiting from loop and “continue” keyword use for continuing
the loop.
There are three Jump statements:
● break statement
● continue statement
● return statement
break statement
The break statement in Java programming language has the following two usages:
● When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
● It can be used to terminate a case in the switch statement
Syntax
break;
Flow Diagram

Example:
/Java Program to demonstrate the use of break statement
public class BreakExample {

 
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break; //breaking the loop
}
System.out.println(i);
}
}
}
Output:
1
2
3
4

Continue
The continue keyword can be used in any of the loop control structures. It causes the loop
to immediately jump to the next iteration of the loop.
● In for loop, the continue keyword causes control to immediately jump to the update
statement.
● In a while loop or do/while loop, control immediately jumps to the Boolean expression.

Syntax
continue;

Flow Diagram

 
Example:1
/Java Program to demonstrate the use of continue statement
//inside the for loop.
public​ ​class​ ContinueExample {
public​ ​static​ ​void​ main(String[] args) {
//for loop
​for​(​int​ i=1;i<=5;i++){
​if​(i==3){
//using continue statement
​continue​;//it will skip the rest statement
}
System.out.println(i);
}
}
}

 
Output:
1
2
4
5
Example:2
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output:
10
20
40
50
Return statement
● return is a reserved keyword in Java i.e, we can’t use it as an identifier.
● It is used to ​exit​ from a method, with or without a value.
Syntax

 
return;
Example :​ Program for return statement
public class MyClass
{
static ​int​ myMethod(int x)
{
​return​ 5 + x;
}
public static void main(String[] args)
{
System.out.println(myMethod(3));
}
}
Output:
8

What are Arrays in Java?


An array is a ​collection of similar types of data​. It is a ​container that holds data (values) of one single
type.
For example, you can create an array that can hold 100 values of integer type. In Java, arrays are a
fundamental construct that allows you to store and access a large number of values conveniently.

Arrays are ​objects which store multiple variables of the same type​. It can hold ​primitive types​ as well
as ​object references​. In fact most of the collection types in Java which are the part of ​java.util​ package use
arrays internally in their functioning. Since Arrays are objects, they are created during runtime .The array
length is fixed.

Arrays in Java ​are homogeneous data structures implemented in Java as objects. Arrays store one or more
values of a specific data type and provide indexed access to store the same. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.

Obtaining an array is a two-step process.

 
● First, you must declare a variable of the desired array type
● Second, you must allocate the memory that will hold the array, using ​new​, and assign it to the array variable

Arrays can be initialized when they are declared. The array will automatically be created large enough to hold the
number of elements you specify in the array initializer. There is no need to use new.
Features of Array

● Arrays are objects


● They can even hold the reference variables of other objects
● They are created during runtime
● They are dynamic, created on the heap
● The Array length is fixed

Array Declaration

First let us get into the ​declaration of arrays which hold primitive types​. The declaration of array
states the type of the element that the array holds followed by the identifier and square braces which indicates
the identifier is array type.

Example 1​:​ Declaring an array which holds elements of integer type.

int MyArray[];

The above statement creates an array reference on the stack.

Declaring Array

int []aiMyArray;
int aiMyArray[];

Creating Arrays
You can create an array by using the new operator with the following syntax −

Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
● It creates an array using new dataType[arraySize].
● t assigns the reference of the newly created array to the variable arrayRefVar.
 
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the ​index​. Array indices are 0-based; that is, they start from
0 to ​arrayRefVar.length-1​.

Example
Following statement declares an array variable, myList, creates an array of 10 elements of double type
and assigns its reference to myList −
double​[]​ myList ​=​ ​new​ ​double​[​10​];
Following picture represents array myList. Here, myList holds ten double values and the indices are
from 0 to 9.

Processing Arrays
When processing array elements, we often use either ​for​ loop or ​foreach​ loop because all of the
elements in an array are of the same type and the size of the array is known.

 
Example
Here is a complete example showing how to create, initialize, and process arrays
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
OUTPUT
1.9
2.9
3.4
3.5
Total is 11.7
 
Max is 3.5

The for each Loops


Introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse
the complete array sequentially without using an index variable.

Example
The following code displays all the elements in the array myList –
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList)
{
System.out.println(element);

}}}

This will produce the following result −

Output
1.9
2.9
3.4
3.5

Passing Arrays to Methods


Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an ​int​ array

Example
public static void printArray(int[] array)
{

 
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the printArray
method to display 3, 1, 2, 6, 4, and 2 −

Example
printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method


A method may also return an array. For example, the following method returns an array that is the
reversal of another array −

Example
public static int[] reverse(int[] list) {
int[] result = new int[list.length];

for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {


result[j] = list[i];
}
return result;
}

Two Dimensional Array


The Two Dimensional Array in Java programming language is nothing but an Array of ​Arrays​. ​In
Java Two Dimensional Array, data stored in row and columns, and we can access the record using both the
row index and column index ​.
If the data is linear, we can use the One Dimensional Array. However, to work with multi-level
data, we have to use the ​Multi​-​Dimensional ​Array​. Two Dimensional Array in Java is the simplest form of
Multi-Dimensional Array​.

 
Example
class TwodimensionalStandard
{
public static void main(String args[])
{
int[][] a={{10,20},{30,40}};//declaration and initialization
System.out.println("Two dimensional array elements are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
}
}
Output:

10

20

 
30

40

You might also like