In this section we will learn how to use if-then, if-the else and switch statements in Java programming.
Controlling your program
We all know that the execution of the statements in a program takes place from top to bottom. We will learn how the different kinds of statement have different effects in looping like decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) in Java programming language.
Selection
In this section we will learn how to use if-then, if-the else and
switch statements in Java programming. These are the two alternative structure
statements in Java.
The if statement
To start with controlling statements in Java, lets have a recap over the
control statements in C++. You must be familiar with the if-then statements in
C++. The if-then statement is the most simpler form of control flow statement.
It directs the program to execute a certain section of code. This code gets
executed if and only if the test evaluates to true. That is the if statement in
Java is a test of any boolean expression. The statement following the if will
only be executed when the boolean expression evaluates to true. On the contrary
if the boolean expression evaluates to false then the statement following the if
will not only be executed.
Lets tweak the example below:
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)
System.out.println("Less than 1");
In the above example if we declare int a = 1, the statements
will show some of the valid boolean expressions to the if statement.
We are talking about if statements here so we can't
forget the else statement here. The if statement is incomplete without
the else statement. The general form of the statement is:
if (condition)
statement1;
else
statement2;
The above format shows that an else statement will be executed whenever an if statement evaluates to false.
For instance,
if (a>1){
System.out.println("greater than 1");
}
else{
System.out.println("smaller than 1");
}
Lets have a look at a slightly different example as shown below:
class compare{
|
The above example shows that we have taken two numbers and we have to find the smallest amongst them. We have applied a condition that if a<b, print 'a is smaller' else print 'b is smaller'. The following is the output which we will get in the command prompt.
C:\javac>javac compare.java C:\javac>java compare a is smaller |
The switch statement
Sometimes it becomes cumbersome to write lengthy
programs using if and if-else statements. To avoid this we can use Switch statements
in Java. The switch statement is used to select multiple alternative execution
paths. This means it allows any number of possible execution paths. However,
this execution depends on the value of a variable or expression. The switch
statement in Java is the best way to test a single expression against a series
of possible values and executing the code.
Here is the general form of switch statement:
switch (expression){
case 1:
code block1
case 2:
code block2
.
.
.
default:
code default;
}
The expression to the switch must be of a type
byte, short, char, or int. Then there is a code block following the switch
statement that comprises of multiple case statements and an optional default
statement.
The execution of the switch statement takes place by comparing the value of the
expression with each of the constants. The comparison of the values of the
expression with each of the constants occurs after the case statements.
Otherwise, the statements after the default statement will be executed.
Now, to terminate a statement following a switch
statement use break statement within the code block. However, its an
optional statement. The break statement is used to make the computer jump to the
end of the switch statement. Remember, if we won't use break statement the
computer will go ahead to execute the statements associated with the next case
after executing the first statement.
Here is an example which will help you to understand more easily:
switch (P { //
assume P is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
For example the following program Switch, declares an int named week whose value represents a day out of the week. The program displays the name of the day, based on the value of week, using the switch statement.
class Switch{
|
In this case, "friday" is printed to standard output.
C:\javac>javac Switch.java C:\javac>java Switch friday |
One other point to note here is that the body of a switch statement is known as
a switch block. The appropriate case gets executed when the switch
statement evaluates its expression.
Iteration
The concept of Iteration has made our life much more
easier. Repetition of similar tasks is what Iteration is and that too without
making any errors. Until now we have learnt how to use selection statements to
perform repetition. Now lets have a quick look at the iteration statements which
have the ability to loop through a set of values to solve real-world problems.
The for Statement
In the world of Java programming, the for loop has made
the life much more easier. It is used to execute a block of code continuously to
accomplish a particular condition. For statement consists of tree parts i.e. initialization,
condition, and iteration.
initialization : It is an expression that sets the value of the loop
control variable. It executes only once.
condition : This must be a boolean expression. It tests the loop
control variable against a target value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop
control variable.
Here is the form of the for loop:
for(initialization; condition; iteration){
//body of the loop
}
For example, a sample for loop may appear as follows:
int i;
for (i=0; i<10; i++)
System.out.println("i = " +i);
In the above example, we have initialized the for loop
by assigning the '0' value to i. The test expression, i < 100, indicates that
the loop should continue as long as i is less than 100. Finally, the increment
statement increments the value of i by one. The statement following the for loop
will be executed as long as the test expression is true as follows:
System.out.println("i = " + i);
Well, we can add more things inside a loop. To do so we can use curly braces to indicate the scope of the for loop. Like,
int i;
for (i=0; i<10; i++) {
MyMethod(i);
System.out.println("i = " + i);
}
There is a simpler way to declare and initialize the variable used in the loop.
For example, in the following code, the variable i is declared directly
within the for loop:
for (int i=0; i<100; i++)
System.out.println("i = " +i);
Lets see a simple example which will help you to understand for loop very easily. In this example we will print 'Hello World' ten times using for loop.
class printDemo{
|
Here is the output:
C:\javac>javac printDemo.java C:\javac>java printDemo Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! |
After learning how to use a for loop, I would like to
introduce another form of for loop to be used for iteration through
collection and arrays. This form has enhanced the working of for loop. This is
the more compact way to use a for loop.
Here we will take an array of 10 numbers.
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, arrayDemo,displays the usage of for loop through arrays.
It shows the variable item that holds the the current value from the
array.
class arrayDemo{
|
Here is the output of the program
C:\javac>javac arrayDemo.java C:\javac>java arrayDemo 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 |
We would like to suggest to use this form of for loop if possible. 0
The while and do-while Statements
Lets try to find out what a while statement does. In a simpler language, the while statement continually executes a block of statements while a particular condition is true. To write a while statement use the following form:
while (expression) {
statement(s)
}
1
Lets see the flow of the execution of the while
statement in steps:
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is
false and exit the while statement.
3. Lastly, If the condition is true it executes each of the statements between
the brackets and then go back to step 1.
For example:
// This is the Hello program in Java
|
In the above example, firstly the condition will be checked in the parentheses, while (i<args.length). If it comes out to be true then it will continue the execution till the last line and will go back to the loop again. However, if its false it will continue the next statement and will exit the while loop. 2
The output is as follows:
C:\javac>javac Bonjour.java C:\javac>java Bonjour Bonjour |
The while statement works as to for loop because the third step loops back to
the top. Remember, the statement inside the loop will not execute if the
condition is false. The statement inside the loop is called the body of the
loop. The value of the variable should be changed in the loop so that the
condition becomes false and the loop terminates.
Have a look at do-while statement now. 3
Here is the syntax:
do {
statement(s)
} while (expression);
Lets tweak an example of do-while loop.
class DoWhileDemo{
|
In the above example, it will enter the loop without checking the condition first and checks the condition after the execution of the statements. That is it will execute the statement once and then it will evaluate the result according to the condition.
The output is as follows: 4
C:\javac>javac DoWhileDemo.java C:\javac>java DoWhileDemo Bonjour Bonjour Bonjour Bonjour Bonjour |
You must have noticed the difference between the while and do-while loop. That is the do-while loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-while loop will be executed once.
Jumping
Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not always the right idea to use because they are cumbersome to read. Using jumping statements like break and continue it is easier to jump out of loops to control other areas of program flow. 5
The break Statement
We use break statement to terminate the loop once the
condition gets satisfied.
Lets see a simple example using break statement.
class BreakDemo{
|
In the above example, we want to print 5 numbers from 0
to 1 at first using for loop as shown. Then we put a condition that 'if
i = = 3', the loop should be terminated. To
terminate the loop after satisfying the condition we use break.
6
It gives the following output:
C:\javac>javac BreakDemo.java C:\javac>java BreakDemo 0 1 2 3 |
The break statement has two forms: labeled and unlabeled. You saw the labeled form in the above example i.e. a labeled break terminates an outer statement. However, an unlabeled break statement terminates the innermost loop like switch, for, while, or do-while statement.
Now observe the example of unlabeled form below. We have used two loops here two print '*'. In this example, if we haven't use break statement thus the loop will continue and it will give the output as shown below. 7
class BreaklabDemo1
|
Output:
C:\javac>javac BreaklabDemo1.java C:\javac>java BreaklabDemo1 * ** *** **** ***** ****** ******* ******** ********* ********** C:\javac> |
However in the following example we have used break statement. In this the inner for loop i.e. "for (int j=0; j<=i; j++)" will be executed first and gets terminated there n then. Then the outer for loop will be executed i.e. "for (int i=0; i<10; i++)". And it will give the output as shown below.
class BreaklabDemo{
|
Output: 8
C:\javac>javac BreaklabDemo.java C:\javac>java BreaklabDemo * ** *** **** ***** ****** ****** ****** ****** ****** C:\javac> |
The continue statement
The continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.
In this program we will see that how the continue statement is used to stop the execution after that.
Here is the code of the program :
public class Continue{ public static void main(String[] args){ Thread t = new Thread(); int a = 0; try{ for (int i=1;i<10;i++) { if (i == 5) { continue; //control will never reach here (after the continue statement). //a = i; } t.sleep(1000); System.out.println("chandan"); System.out.println("Value of a : " + a); } } catch(InterruptedException e){} } } |
Output of the program :
If we write the code in the given program like this :
if (i == 5 )
{
continue;
a = i;
}
Then the program will generate an error on compile time like :
C:\chandan>javac Continue.java
Continue.java:12: unreachable statement
a = i;
^
1 error
If we write the code in the given program like this :
if (i == 5 )
{
continue;
}
Then the program prints the output like :
C:\chandan>javac Continue.java |