We use control statements in Java to determine which statement must be executed and when. They are helpful for decision-making in real-time. In this Control Statements in Java blog, you will explore control statements like If, If-else, Nested if, While, Switch, etc.
A control statement works as a determiner for deciding the next task of the other statements whether to execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute first between the two. In Java, the control statements are divided into three categories which are selection statements, iteration statements, and jump statements. A program can execute from top to bottom but if we use a control statement. We can set an order for executing a program based on values and logic.
Table of Contents
If you would like to become a Core Java Certified professional, then visit Mindmajix - A Global online training platform:" Core java Certification Training Course".This course will help you to achieve excellence in this domain.
Decision-making statements are statements that decides what to execute and when. They are similar to decision making in real-time. Control flow statements control the flow of a program’s execution. Here flow of execution will be based on the state of a program. We have 4 decision-making statements available in Java.
Simple if the statement is the basis of decision-making statements in Java. It decides if a certain amount of code should be executed based on the condition.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Statement 2; //this will be executed irrespective of condition becomes true or false
Example:
class ifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
After if statement
In if…else statement, if the condition is true then statements in if block will be executed but if it comes out as false then else block will be executed.
Syntax:
if (condition) {
Statemen 1; //if condition becomes true then this will be executed
}
Example:
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Output:
i is less than 10 After if else statement
Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside another if…else statement.
Syntax:
if (condition1) {
Statemen 1; //executed when condition1 is true
if (condition2) {
Statement 2; //executed when condition2 is true
}
else {
Statement 3; //executed when condition2 is false
}
}
Example:
class nestedifTest
{
public static void main(String args[])
{
int x = 25;
if (x > 10)
{
if (x%2==0)
System.out.println("i is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else
{
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
}
}
Output:
i is greater than 10 and odd number
After nested if statement
Top 10 Programming Languages that you need to watch out to boost your career in 2021
<iframe width="560" height="315" src="https://www.youtube.com/embed/FpgoViYrcEE" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
if…else if statements will be used when we need to compare the value with more than 2 conditions. They are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last else statement will be executed.
Syntax:
if (condition2) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
.
.
else {
Statement 3; //executed when no matching condition found
}
Example:
class ifelseifTest
{
public static void main(String args[])
{
int x = 2;
if (x > 10)
{
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else
{
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
Output:
i is less than 10 After if else if ladder statement
Java switch statement compares the value and executes one of the case blocks based on the condition. It is same as if…else if ladder. Below are some points to consider while working with switch statements:
Let us understand it through one example.
class switchDemo{
public static void main(String args[]){
int i=2;
switch(i){
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}
Looping statements are the statements which executes a block of code repeatedly until some condition meet to the criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.
While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a Boolean expression. If int or string is used instead, compile will give the error.
Syntax:
while (condition)
{
statement1;
}
Example:
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Output:
1 3 5 7 9
Do…while works same as while loop. It has only one difference that in do…while condition is checked after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of loop will be executed at least once before checking the condition
Syntax:
do{
statement1;
}while(condition);
Example: here
class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;
do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}
Output:
10
It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is easy to debug structure in Java.
Syntax:
for (initialization; condition; increment/decrement)
{
statement;
}
Example:
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:
1 2 3 4 5
For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to increment the value. It returns the elements from the array or collection one by one.
Example:
class foreachDemo{
public static void main(String args[]){
int a[] = {10,15,20,25,30};
for (int i : a) {
System.out.println(i);
}
}
Output:
10 15 20 25 30
Branching statements jump from one statement to another and transfer the execution flow. There are 3 branching statements in Java.
------ Related Article: Java Operators -----
Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the innermost loop.
Example:
class breakTest
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}
Output:
0 1 2 3 4 After loop
Continue statement works same as break but the difference is it only comes out of loop for that iteration and continue to execute the code for next iterations. So it only bypasses the current iteration.
Example:
class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
// only even numbers will be printed
System.out.print(j + " ");
}
}
}
Output:
0 2 4 6 8
The return statement is used to transfer the control back to the calling method. The compiler will always bypass any sentences after the return statement. So, it must be at the end of any method. They can also return a value to the calling method.
Example: Here method getwebURL() returns the current URL to the caller method.
public String getwebURL()
{
String vURL= null;
try {
vURL= driver.getCurrentUrl();
}
catch(Exception e) {
System.out.println("Exception occured while getting the current url : "+e.getStackTrace());
}
return vURL;
}
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
Core Java Training | Dec 03 to Dec 18 | View Details |
Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.