Control Statements In Java

Posted By : Hany Yadav | 29-Jan-2021

Java

Loading...

LOOPS:-

In Java, loops are used when we want our programme to execute a few sets of instructions again and again.

For example:-Printing number 1 to 10 etc

It makes it easier to tell the machine to execute the following set of instructions again and again until the condition gets false.

TYPES OF LOOPS:-

1-While Loop

2-do-While Loop

3-For Loop

1-While Loop:-

In while loop first condition is checked if the condition is true then the loop is executed and if the condition is false then the loop is not executed.

Syntax:-

While(Condition)

{

//Statement

}

Example:-

int b=9;

While(b<=9)

{

System.out.println(b);

b++;

}

Output:-

9

2-do-While Loop:-

do-while loop is similar to a while loop but if the condition is false then the loop is executed at least once.

Syntax:-

do{

//Statement

}While(condition);

Example:-

int b=10;

do{

System.out.println(b);

b++;

}While(b<5);

Output:-

10

In the above example, we have applied condition in while (b<5) it will check the condition after the execution of do loop code and if the condition is false then again do loop code is not executed.

3-For loop:-

It is also a loop supported by Java and it is widely used in this loop firstly variable is initialized and then condition is defined separated by semicolon(;) and then update.

Syntax:-

for(initialize;condition;update)

{

//Statement;

}

Example:-

for(i=0;i<=1;i++)

{

System.out.println(i);

}

Output:-

0

1

SWITCH STATEMENT:-

In Java, we are using statements in order to control the flow of execution if we want to check the conditions and execute code on the basis of conditions then we will use control statements and switch statement is one of the control statement used to control the flow of execution of program it is used when we have to make a choice between number of alternatives.

Syntax:-

Switch(var){

Case C1:

//Statement;

break;

Case C2:

//Statement;

break;

Case C3:

//Statement;

break;

}

Example:-

public class example{

Switch(age){

Case 18;

System.out.println("You are going to become an adult")

Case 23;

System.out.println("You are going to join a job")

Case 60;

System.out.println("You are going to get retired")

}

Enter input from keyboard

23

Output:-

You are going to join a job

At Oodles ERP, we provide complete enterprise solutions to overcome complex business challenges and streamline inbound/outbound processes. Our Web application development services enable organizations to enhance their business productivity and improve operational efficiency. For more information, contact us at [email protected]