Flow Control Statements
Flow Control Statements
Statements In Java
Java Statements are divided into 3 categories:
1) Selection Statements
2) Iteration Statements(Loops)
3) Jump Statements
1) Selection Statements:
i) if Statement
ii) if else Statement
iii) if else if …. else Statement
iv) Nested if Statement
v) switch Statement
2) Iteration Statements(Loops):
i) while loop
ii) do while loop
iii) for loop
iv) Enhanced for loop (or) for each loop
v) Nested loops
3) Jump Statements:
i) break Statement
ii) break LABEL Statement
iii) continue Statement
iv) continue LABEL Statement
v) return Statement
i) if Statement:
It is used to express the condition. If block is executed if the condition is true.
Example:
class Demo
{
public static void main(String args[])
{
int a=5;
if(a>0)
{
System.out.println(“Positive Number”);
}
}
}
Example:
class Demo
{
public static void main(String args[])
{
int a=5;
if(a>0)
{
System.out.println(“Positive Number”);
}
else
{
System.out.println(“Negative Number”);
}
}
}
Example:
class Demo
{
public static void main(String args[])
{
int a=5;
if(a>0)
{
System.out.println(“Positive Number”);
}
else if(a<0)
{
System.out.println(“Negative Number”);
}
else
{
System.out.println(“Zero”);
}
}
}
Example:
class Demo
{
public static void main(String args[])
{
int a=5;
if(a>0)
{
if(a%2==0)
System.out.println(“Even Number”);
else
System.out.println(“Odd Number”);
}
else
{
if(a<0)
System.out.println(“Negative Number”);
else
System.out.println(“Zero”);
}
}
}
i) while loop:
The body of while loop is repeatedly executed until the condition becomes false.
Example:
class Demo
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
The body of do while loop is repeatedly executed until the condition becomes
false.
Do while loop is executed at least once
Example:
class Demo
{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
Example:
class Demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
i) break Statement:
It terminates the nearest enclosing loop or switch statement.
Example:
class Demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==5)
break;
System.out.println(i);
}
}
}
Example:
class Demo
{
public static void main(String args[])
{
FIRST: for(int i=1;i<=3;i++)
{
SECOND: for(int j=1;j<=10;j++)
{
if(j==5)
break FIRST;
System.out.println(j);
}
}
}
}
iii) continue Statement: It passes the control to the next iteration of a loop.
Example:
class Demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.println(i);
}
}
}
Example:
class Demo
{
public static void main(String args[])
{
FIRST: for(int i=1;i<=3;i++)
{
SECOND: for(int j=1;j<=10;j++)
{
if(j==5)
continue FIRST;
System.out.println(j);
}
}
}
}