Table of Contents
Control Statements in Java
Up to this we have discussed about computer science and JAVA. You have created programs which used sequential execution. A program is a set of statements, which normally executed line by line in the order they appear. This approach is fine when conditional evaluation or repetitions of certain statements are not necessary.
However, in real time there are number of scenarios where we may have to write code based on a certain criteria or repeat a set of statements until a specific condition is met.
For example you may need to write a program for assigning grades to the students according to the following conditions
Percentage and the respective grades given below :
> 90% – Grade O,
> = 74% and < 90% – Grade A
> = 61% and <74% – Grade B
> =51% and < 61% – Grade C
> =35% and < 51% – Grade D
< 35% – Grade F
Decision making and branching
The selection statement of java is used for branching and decision making within a program. As we have seen, this required a kind of decision making to check whether a particular condition is met or not and then execute certain set of statements accordingly.
When a program jumps to another portion of a program based on the condition is known as conditional branching. If branching takes place without condition is called as unconditional branching. JAVA supports both types of branching or decision making statements.
These statements are also known as decision making statements.
- if
- switch .. case
- conditional operator
If Conditional statement
A few examples of decision making using if statement is
if (you are bored)
Go for picnic
if (error in program)
Debug the program
if (number is not divisible by 2)
number is odd
else
number is even
the if statement can have other forms for different conditions depending upon the complexity of the conditions to be tested
a. if statements
b. if-else statements
c. Nested if … else
d. else-if Ladder
1. if Statement
Syntax :
if(condition or test expression)
{
statement True Block;
}
Statement – false
If the test condition or expression is true, the statements in the true block will get executed, and the program control is passed to statement –false. if the test condition or expression is false, the statements in the statement true block will be ignored and the program control is passed to the statement – false.
Let us consider a program for simple if
import java.util.Scanner;
public class SimpleIf
{
public static void main(String[] args)
{
char ch;
int posnum;
Scanner sc = new Scanner(System.in);
System.out.println(“Please enter an alphabet :”);
ch=sc.next().charAt(0);
if (ch >=’A’&& ch<=’Z’||ch>=’a’&&ch<=’z’ )
{
System.out.println(“Alphabet”+ch);
}
System.out.println(“Program completes”);
}
}
Output:
Please enter an alphabet : v
Alphabet v
Program completes
In the above program the if checks whether a given character is an alphabet or not.
2. If.. else Statement
The if..else statement, if the specified condition in the if the statement is false, then the statement after the else keyword (that can be a block) will execute. The general form of if else is as follows :
If(condition or test expression)
{
True Block statements
}
else
{
flase block statements
}
Statement- n
If the condition or test expression is true, then the true block statements will be executed and flase block will not be executed. If the condition or test expression is false, then the false block statements will be executed. In either case either true block or false block will get executed, but not both.Once , one of these blocks completes their execution the program control is transferred to statement-n.
Example :
import java.util.Scanner;
public class ExIfElse
{
public static void main(String[] args)
{
int uAge;
Scanner sc = new Scanner(System.in);
System.out.print(“Enter Your Age: “);
uAge = sc.nextInt();
if (uAge >= 18)
{
System.out.println(“You are Major “);
}
else
{
System.out.println(“You are Minor”);
}
}
}
This program accepts User age from user and checks whether major or minor. If the test expression result is true ie., uAge>18, then if block will get executed. If the test expression result is flase ie., uAge>18, then else block will get executed.
Output:
Enter Your Age: 25
You are Major
3. Nested if .. else statements:
When a series of decisions are involved, we can use more than one if … else statement in a nested form:
The logic of the above nested if .. else is as follows: if test expression_1 results into true, then program control is passed to inner if statement and evaluates test expression_2, depending upon the truth value of the test expression _1 returns false, the program control is passed to else part of the outer if and statement _3 will get executed. Once, the if block (outer if or inner if) completes the execution, the program control will be transferred to statement_x An example program using nested if … else
Example :
import java.util.Scanner;
public class NestedIfElseEx
{
public static void main(String[] args)
{
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print(“Please enter Age: “);
age = inputDevice.nextInt();
if (age >= 18 && age <= 35)
{
System.out.println(“between 18-35 “);
}
else if (age > 35 && age <= 60)
{
System.out.println(“between 36-60”);
}
else
{
System.out.println(“not matched”);
}
}
}
4. else if ladder
Another way of putting ifs together is using a chain of ifs, in which the statement associated with each else is again an if. This logical structure is ifs is commonly referred as else if ladder and is used when multi-path decisions are involved. Else if ladder takes the following form
If (test expression-1)
Statement-1;
Else if (test expression-2)
Statement-2;
Else if(test expression-3)
Statement-3;
Else
Default statement;
Statement-x;
In else if ladder, the conditions are evaluated from the top of the ladder to downwards. As soon as the true condition is found, the statement associated with it is executed and the program control is passed on to the statement-x. when all the conditions becomes false, then the final else containing the default statement will get executed, and then the program control is transferred to statement-x.
Example :
public class ElseIfLadderEx
{
public static void main(String args[])
{
int per = 80;
if( per >= 75 && per<=100 )
{
System.out.print(“Grade O”);
}
else if( per >= 60 )
{
System.out.print(“Grade A”);
}
else if( per >= 50 )
{
System.out.print(“Grade B”);
}
else if( per >= 35 )
{
System.out.print(“Grade C”);
}
else
{
System.out.print(“Fail”);
}
}
}
Output:
Grade O
5. switch … case statement:
C supports a multi-way decision statement known as switch … case. The switch statement tests the value of a given variable (or expression) against a set of case values and when a match is found, the block of statements associated with that case are executed. The general form of switch… case statement is as follows:
Switch (expression)
{
Case val-1:
Stsement-block-1;
Break;
Case val-2:
Stsement-block-2;
Break;
Case val-3:
Stsement-block-3;
Break;
……
default :
default -block;
break;
}
Statement-x;
Here the expression associated with switch is an integer or character expression. The values (value-1, value-2…)associated with case are known as case labels. Each of these labels must be unique within a switch statement. Each case label must end with a colon (:).
Example :
import java.util.Scanner;
public class ExSwitch
{
public static void main(String[] args)
{
int day;
Scanner sc = new Scanner(System.in);
System.out.print(“Please enter number(1 for weekday 2 for weekend): “);
day = sc.nextInt();
switch (day)
{
case 1:
System.out.println(“Weekday”);
break;
case 2:
System.out.println(“weekend”);
break;
default:
System.out.println(“not matched”);
break;
}
}
}
the ? operator
Java language has a special operator, useful for making two-way decisions. This operator is a combination of ? and : and takes three operands. This operator is popularly known as conditional operator or ternary operator. The general form of conditional operator is as follows:
Conditional expression ? expression-1 : expression-2
The conditional expression is evaluated first. If the result is true, expression-1 is evaluated and returned as the value of the conditional expression. Otherwise expression-2 is evaluated and its value is returned. In general conditional operator is used as substitute for simple for simple if … else statement.
Example :
int a =10;
int b =20;
int c;
if (a>b)
C=a;
else
C=b;
//This if else this code segment can be written as follows using ternary operator
C=(a>b) ? a : b
public class CondEx
{
public static void main(String args[])
{
int a, b, c;
a = 30;
b = 55;
c = (a > b) ? a: b;
System.out.println(“Biggest Value is: ” + c);
}
}
Output:
Biggest Value is: 55
Loop Statements
In some cases we need to execute some set of statements, until condition is satisfied. This is called iteration. loop statements will be executed the same set of instructions, until a termination condition is met.
Following are the java Loops
- while
- for
- do-while
- for-each
While
The simples to fall the looping controls is in java is while statement. The general form of while statement is as follows:
Syntax:
Initialization of loop control variable;
while (condition)
{
Body of the loop
}
If the condition is true the set of statements in the block executes. The condition returns a Boolean value. When the condition is 0 or false, control goes out of the while loop
An example program using while statement
public class Loop While
{
public static void main(String []args)
{
int i = 0;
while(i <5)
{
System.out.println(“Value::”+i);
i++;
}
}
}
Output:-
Value :: 0
Value :: 1
Value :: 2
Value :: 3
Value :: 4
The do-while loop:
This loop also resembles while loop, but the difference is that do -while evaluates its condition at the end of the loop, instead of the first.The do-while loop executes at least once, then it will check the conditionprior to the next iteration.
Do…while is an exit -controlled looping structure, i.e., the loop body will be executed first before evaluating loop control statement. Do … whitle takes the follwong form:
Syntax:
Initialization of loop control variable; do
{
Bodyoftheloop;
} while (condition);
Example:-
public class Ex Do While
{
public static void main(String []args)
{
int i = 0;
do
{
System.out.println(“value::”+i);
i++;
}while (i<5);
}
}
Output:-
Value::0
Value::1
Value::2
Value::3
Value::4
The for loop:-
For loop works similar to other loops, but it is simpler one. Initialization, condition, decrement or increment or loop runner will be written in one line.
Syntax:
for (initialization; condition; increment or decrement statement)
{
Loop body
}
The for loop starts by initializing the loop variable. The condition will be evaluated for every iteration before the block statements executes. If the condition is true then only the statement (that is usually a block) will execute. The increment or decrement statement executes every time, after every iteration.
The execution of the for statement is as follows:
Initialization of the loop control variable is done first, using assignment statements such as i= 1 or count = 10 etc. here I and count are referred as loop control variables.
Example:-
public class ExWhile
{
public static void main(String []args)
{
int i;
for(i=0;i < 5;i++)
{
System.out.println(“Value::”+i);
}
}
}
Output:-
Value::0
Value::1
Value::2
Value::3
Value::4
For each loop (Enhanced for loop)
This was introduced in Java5. This loop is basically used to traverse the array or collection elements. In the most recent version, it is also called as lambda expression.
Syntax:
for(Type Identifier:expression)
{
//statements;
}
Example:-
public class For Each Ex
{
public static void main(String []args)
{
int[] i = {1, 2, 3, 4, 5 };
for(int j: i)
{
System.out.println(“value::”+j);
}
}
}
Output:-
value::1 value::2 value::3 value::4 value: : 5
Jump Statements
Jump statements are used to un conditionally transfer the program control to an other part of the program.
Java provides the following jump statements:
- break statement
- continue statement
Break Statement
The break statement immediately quits the current iteration and goes to the first statement, following the loop. Another form of break is used in the switch statement.
Example:-
public class Break Example{
public static void main(String [] args)
{
for(inti=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
}
Output:-
1
2
3
4
Continue Statement
The continue statement is used when you want to continue running the loop, with the next iteration, and want to skip the rest of the statements of the body, forthe current iteration. It is written by writing continue keyword.
Example:-
public class Continue Example
{
public static void main(String []args)
{
for (int i=1; i<=10; i++)
{
if(i==5)
{
//usingcontinuestatement
continue; //it will skip the rest statement
}
System.out.println(i);
}
}
}
Output:-
1
2
3
4
Add Your Heading Text Here
You May Like to Browers More


