Java Week 4

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

Control Flow Statement

By default, programs are executed generally from top to bottom, in the order that

they appear. These instructions are always executed in sequence, that is, one after

the other, from the beginning to the end of the main method. This order of

execution is usually too restrictive when complex task needs to be carried out.

Hence, the need to have much more control over the order in which instructions is

executed. Various control flow statements will be discussed in this chapter.

Decision-Making Statement

The if Statement

The if statement is the most basic of all the control flow statement. It tells your

program to execute a certain section of code only if a particular test evaluates to

true. The primary structure for an if-statement in Java is:

if ( CONDITION )
{
STATEMENTS
}
An example code is given below:
import java . util . Scanner;
public class Temperature
{
public static void main( String [] args )
{
Scanner keyboard = new Scanner( System.in );
System.out.print( "What is the average high temperature in August in
your area? : " );
double temp = keyboard.nextDouble ();
if ( temp > 90.0 )
{
System.out.println( "Wow! That must be very hot!");
}
}
}

Here is the if-statement appearing in the code:


if ( temp > 90.0 )
{
System.out.println( "Wow! That must be very hot!");
}
In the code above, the program prints the statement "Wow! That must be very

hot!" if the value the user enters is greater than 90.0 and prints nothing if the value

the user enters is 90.0 and below.

The if… else Statement

An extended version of an if statement exists in Java to state an alternative course

of action. This extended form of selection is the if…else statement. As the name

implies, the instructions to be executed if the test evaluates to false are preceded by

the Java keyword else. An example code is given below:

import java.util.Scanner;
public class DisplayResult
{
public static void main(String[] args)
{
int mark;
Scanner keyboard = new Scanner(System.in);
System.out.println("What exam mark did you get? ");
mark = keyboard.nextInt();
if (mark >= 40)
{
// executed when test is true
System.out.println("Congratulations, you passed");
}
else
{
// executed when test is false
System.out.println("I'm sorry, but you failed");
}
System.out.println("Good luck with your other exams");
}
}

This program checks a student’s exam mark and tells the student whether or not he

or she has passed (based on the pass mark score which is 40), before displaying a

good luck message on the screen.

The switch Statement

The switch statement works exactly the same way as a set of nested if statements,

but is more compact and readable. The body of a switch statement is known as a

Switch block. Another point of interest is the break statement. Each break
statement terminates the enclosing switch statement. The break statements are

necessary because without them, statements in switch blocks fall through

A switch statement may be used when:

 Only one variable is being checked in each condition

 The check involves specific values of that variable and not range of values

An example code is given below:

public class SwitchDemo


{
public static void main(String[] args)
{
int month = 8;
String monthString;
Switch (month)
{
Case 1: monthString = “January”
break;
Case 2: monthString = “February”
break;
Case 3: monthString = “March”
break;
Case 4: monthString = “April”
break;
Case 5: monthString = “May”
break;
Case 6: monthString = “June”
break;
Case 7: monthString = “July”
break;
Case 8: monthString = “August”
break;
Case 9: monthString = “September”
break;
Case 10: monthString = “October”
break;
Case 11: monthString = “November”
break;
Case 12: monthString = “December”
break;
Case default: monthString = “Invalid Month”
break;
}
System.out.println(monthString);
}
}
In the code above, the program prints out August. This is so because variable

“month” has already been declared to be “8” which stands for August.
Looping Statement

Iteration is the form of program control that allows us to instruct the computer to

carry out a task several times by repeating a section of code. For this reason, this

form of control is often also referred to as repetition. The programming structure

that is used to control this repetition is often called a loop; we say that the loop

iterates a certain number of times. There are three types of loop in Java:

 for loop;

 while loop;

 do…while loop.

The “for” loop

The “for loop” statement provides a compact way to iterate over a range of values.

If we wish to repeat a section of code a fixed number of times we would use the for

loop. An example code is given below:


public class ForDemo
{
public static void main(String[] args)
{
For (int i = 1; i < 11; i++)
{
System.out.println(“Count is:” + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
The program above can be re-written as

public class ForDemo


{
public static void main(String[] args)
{
System.out.println(“Count is:” + 1);
System.out.println(“Count is:” + 2);
System.out.println(“Count is:” + 3);
System.out.println(“Count is:” + 4);
System.out.println(“Count is:” + 5);
System.out.println(“Count is:” + 6);
System.out.println(“Count is:” + 7);
System.out.println(“Count is:” + 8);
System.out.println(“Count is:” + 9);
System.out.println(“Count is:” + 10);
}
}

This code will produce the same result as the one with the for loop. But using the

for loop will save a programmer a lot of time as it is easy to use, not time

consuming and also memory efficient.


The “while” loop

The for loop is an often used construct to implement fixed repetitions. Sometimes,

however, a repetition is required that is not fixed and a for loop is not the best one

to use in such a case. Consider the following scenarios, for example:

• A racing game that repeatedly moves a car around a track until the car crashes;

• A ticket issuing program that repeatedly offers tickets for sale until the user

chooses to quit the program;

• A password checking program that does not let a user into an application until he

or she enters the right password.

Each of the above cases involves repetition; however, the number of repetitions is

not fixed but depends upon some condition. The while loop offers one type of non-

fixed iteration. The syntax for constructing this loop in Java is as follows:

while ( // test goes here )


{
// instruction(s) to be repeated go here
}
The “ do…while” loop

The do…while loop is another variable loop construct, but, unlike the while loop,

the do…while loop has its test at the end of the loop rather than at the beginning.

The syntax of a do…while loop is given below:

do
{
// instruction(s) to be repeated go here
}
while ( /* test goes here */ );

The difference between the while loop and the do…while loop is that the while

loop evaluates its expression at the top of the loop whereas the do…while loop

evaluates its expression at the bottom of the loop. Therefore, the statements within

the do blocks are always executed at least once even if the condition happens to be

false, whereas it’s possible that no statements are executed in the while loop if the

first condition happens to be false.


Branching Statement

The Break Statement

The Break statement in Java is used to terminate from a loop (i.e. for loop, while

loop and do.. while loop) immediately or terminate a sequence in a switch

statement. An example code is given below for a break statement in a loop.

public class ForDemo


{
public static void main(String[] args)
{
For (int i = 0; i < 10; i++)
{
//Terminate the loop when I is 5
If ( i = = 5 )
break ;
System.out.println(“i :” + i );
}
System.out.println(“Out of loop”);
}
}
OUTPUT
i:0
i:1
i:2
i:3
i:4
Out of loop

The Continue Statement

The continue statement skips the current iteration of a loop and jumps to the next

iteration of the loop immediately. An example code is given below for a continue

statement in a loop.

public class ForDemo


{
public static void main(String[] args)
{
For (int i = 0; i < 10; i++)
{
//If the number is 2, skip and continue
If ( i = = 2 )
continue;
System.out.print(i + “ ” );
}
}
}

OUTPUT
013456789

The Return Statement

A return statement causes the program control to transfer back to the caller of a

method. Every method in Java is declared with a return type and it is mandatory

for all java methods. A return type may be a primitive type like int, float, double,

a reference type or void type (returns nothing). There are a few important things

to understand about returning the values. The type of data returned by a method

must be compatible with the return type specified by the method. For instance, if

the return type of some method is Boolean, we cannot return an integer. The

variable receiving the value returned by a method must also be compatible with the

return type specified for the method. The parameters can be passed in a sequence

and they must be accepted by the method in the same sequence.

You might also like