3 Control Statements — Java Programming
3.1 Introduction
Control structures are used for repetition, which permit Java programs to perform actions repeatedly. In this chapter you will learn about the control statements, and you’ll be motivated for the need of repetition. You will also write and run a few programs based on each of the control statements.
3.2 The control statements
Programming languages uses control statements to cause the flow of execution to advance and branch based on changes to the state of the program. Java’s program control statements are:
- Selection statements: if, if-else-if, switch
- Iteration: while, do-while, for
- Jump: break, continue and return
Let us understand each of them.
3.2.1 if statement
The general form of if statement is:
if(condition) statement;
If the condition is evaluated to true then the enclosed statement is to be executed otherwise not. The control goes to next instruction following the if statement.
Consider the following code fragment:
int i=12; if(i>10) System.out.println("i >10 is true"); //output will be i >10 is true
We can also add multiple statements in { } when a condition evaluates to true as below.
int i=2; if (i<=2){ i=i-1; System.out.println(i); //prints 1 }
3.2.2 if-else statement
The simple if statement does not specify what is to be done if condition evaluates to false. The if-else statement specifies what is to be done when the condition evaluates to both true and false.
The general form is:
if(condition) { statements } else { statements }
Program.
if(i<10) { system.out.println("i <10); } else{ system.out.println(“i >10); }
3.2.3 if-else if-else
If we have multiple conditions , the we use if-else if-else. The general form of if-else if-else is:
if(condition) { Statements block1 } else if{ statements block2 } else{ statements block3 }
Program 3.1. Program to demonstrate conditions. Print the day of the week using if-else if-else
// conditionsDemo.java // click here for code public class conditionsDemo { public static void main (String args[]) { int i; i = 4; // i is the week day number if (i == 0) { System.out.println ("it is Sunday"); } else if (i == 1) { System.out.println ("it is Monday"); } else if (i == 2) { System.out.println ("it is Tuesday"); } else if (i == 3) { System.out.println ("it is Wednesday"); } else if (i == 4) { System.out.println ("it is Thursday"); } else if (i == 5) { System.out.println ("it is Friday"); } else if (i == 6) { System.out.println ("it is Saturday"); } } } //Output: //it is Thursday
3.2.4 Nested if
Nested if’s are allowed in Java. Nested if means an if statement within an if statement.
3.2.5 Complex conditions in if
We can also have complex conditions in if and else. The following program demonstrates the use of complex conditions.
Program 3.2. Program to print season for given month using else-if.
//seasonDemo.java //click here for code class seasonDemo { public static void main (String args[]) { int month = 5; String season; if (month == 12 || month == 1 || month == 2) season = "winter"; else if (month == 3 || month == 4 || month == 5) season = "spring"; else if (month == 6 || month == 7 || month == 8) season = "summer"; else if (month == 9 || month == 10 || month == 11) season = "autumn"; else season = "invalid month"; System.out.println ("the season is " + season); } } //output //the season is spring
3.2.4 Conditional operator
The conditional/ternary operator of C is valid in Java too.
The general form is:
Expression ? true-result : false-result
If expression evaluates to true the statement true-result gets evaluated otherwise false-result gets evaluated.
Program 3.3. Using the ternary operator
//ternaryDemo.java //click here for code public class ternaryDemo { public static void main (String[] args) { int i, result1, result2; i = 1; result1 = (i == 1) ? 1 : 0; // evaluates to true System.out.println ("result is: " + result1); result2 = (i == 2) ? 1 : 0; //evaluates to false System.out.println ("result is: " + result2); } } // output: //result is: 1 //result is: 0
3.2.5 The Switch statement
This is a multi way branch statement.
The general form is:
Switch(expression){ case value 1; //statements break; case value 2; //statements break; // remaining case statements case value n; //statements break; default: //default sequence }
If break is missing, the next case is also evaluated. If break is present the control comes out of the switch block.
Program 3.4 Repeat conditionsDemo.java with switch statement
// condition-switch.java //Program to print day of the week using switch statement //click here for code public class condition-switch { public static void main(String args[]) { int i; i=4; switch(i) { case 0: System.out.println("it is sunday"); break; case 1: System.out.println("it is Monday"); break; case 2: System.out.println("it is Tuesday"); break; case 3: System.out.println("it is Wednesday"); break; case 4: System.out.println("it is Thursday"); break; case 5: System.out.println("it is Friday"); break; case 6: System.out.println("it is Saturday"); break; default: System.out.println("invalid"); break; } } } //output it is Thursday
Program 3.5 Demonstrating switch statement for printing the season.
// season-switch.java // click here for code class season-switch { public static void main(String args[]) { int month=5; String season; switch(month) { case 12: case 1: case 2: season="winter"; break; case 3: case 4: case 5: season="winter"; break; case 6: case 7: case 8: season="winter"; break; case 9: case 10: case 11: season="winter"; break; default: season="invalid month"; } System.out.println("the season is "+season); } } /* Output: the season is winter */
3.2.6 while loop
The while loop helps in executing a set of statements as long as the condition is true.
The general form of while loop is
while(condition){ //body of loop }
The body of the loop is executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop.
Program 3.6. Program to add ‘n’ numbers using while
// add-while.java // click here for code class add-while { public static void main(String args[]) { int n=10,sum=0; while(n>0) { // this loop executes until n becomes equal to 0 sum=sum+n; n--; } System.out.println("sum="+sum); } } /*Output: sum=55 */
3.2.7 do-while loop
The do-while loop is slightly different from while loop. It executes the body of the loop at least once and then checks the condition.
General form of do-while loop is
do{ //body of the loop } while(condition);
Program 3.7: To add first ‘n’ numbers using do-while
// add-do-while.java // click here for code class add-do-while { public static void main(String args[]) { int n=10,sum=0,i=0; do { sum=sum+i; i++; } while(i<=n); // condition is checked after the body of the loop is executed System.out.println("sum="+=sum); } } /* Output: sum=55 */
3.2.8 for loop
The statements in the body of the for loop are executed repeatedly until the condition is true on a given variable which is initialised and is modified as per the expression given in iteration.
The general form is
for(initialization; condition; iteration) { //body }
In the for loop, initialization is done first before the control gets into the body of the for loop. Next the condition is evaluated and if it is true then the statements in the body of the loop are executed. After completing the execution of all statements in the body of the for loop, the expression in iteration is evaluated. The above steps of checking condition and iteration expression evaluation are done repeatedly until the condition becomes false.
//factorial.java //click here for code class factorial { public static void main(String args[]) { int n=5, fact=1,i; for (i=1;i<=5;i++) fact=fact*i; // this statement is iterated as long as i<=5 System.out.println("fact="+fact); } } /* Output: fact=120 */
The usage of for loop is similar to its usage in C or C++. Nesting of for loops is allowed in Java.
Program 3.9 Program to list all ASCII characters
//asciiChars.java //click here for code public class asciiChars { public static void main(String args[]) { for(char c=0; c<128; c++) if(c!=26) System.out.println("vale:"+(int)c+"character:"+c);); } } /* Output: .... value:33 character:! value:34 character:" value:35 character:# value:36 character:$ value:37 character:% value:38 character:& value:39 character:' value:40 character:( value:41 character:) value:42 character:* value:43 character:+ value:44 character:, value:45 character:- value:46 character:. value:47 character:/ value:48 character:0 value:49 character:1 value:50 character:2 value:51 character:3 value:52 character:4 value:53 character:5 value:54 character:6 value:55 character:7 value:56 character:8 value:57 character:9 value:58 character:: value:59 character:; value:60 character:< value:61 character:= value:62 character:> value:63 character:? value:64 character:@ value:65 character:A ..... */
3.2.9 Simple break statement
The break statement makes the control exit from that particular loop where it is executed.
Program 3.10 Find whether a given alphabet is vowel or consonant
//vowelsConsonants.java //click here for code public class vowelsConsonants { public static void main(String args[]) { for(int i=0;i<10;i++) { char c=(char)(Math.random()*26+'a'); // random character System.out.print(c+":"); switch(c) { case 'a':case 'e':case 'i':case 'o':case 'u': System.out.println("vowel"); break; default: System.out.println("consonant"); } } } } /* Output: j:consonant f:consonant i:vowel i:vowel s:consonant c:consonant t:consonant v:consonant z:consonant k:consonant */
3.2.10 Continue
Using continue statement we can exit the loop or continue from the beginning of the loop
Program 3.11 Program to demonstrate the use of continue statement
//continueDemo.java //click here for code class continueDemo { public static void main(String args[]) { for(int i=1;i<10;i++) { System.out.println("i="+i); if(i%2!=0) continue; // when i=1, i%2 is 0 so i=1 is printed only once. System.out.println("i="+i); } } } /*Output: i=1 i=2 i=2 i=3 i=4 i=4 i=5 i=6 i=6 i=7 i=8 i=8 i=9 */
3.2.11 break statement as a form of goto
The general form of labelled break is break;
When a break statement is executed, control is transferred out of the named block of code.
//breakStmt.java //click here to code class breakStmt { public static void main(String args[]) { boolean t=true; first: // name of the first block { //statements of the first block second: // name of the second block { //statements of the second block third: // name of the third block { //statements of the third block System.out.println("this won't execute"); } System.out.println("This will also not work"); } System.out.println("THis is after second block"); } } } /* Output: this won't execute This will also not work This is after second block */
3.2.12 The return statement
The return is used to return from a method.
return;
Simply use it as above wherever necessary and the control returns to the calling method
3.3 Summary
You are introduced with if, if-else, if-elseif-else, for, while, do while loops. You are introduced to the concepts of return, break, continue, labelled break.