Condition Statements In Java


Condition Statements In Java

Control Statements in any programming language are used to branch and divert the control of execution based on a modification to the state of the program. In Java, the control statements can be grouped into three categories:

Selection Statements or Decision-Making statements:

These statements are used to control the flow of execution of the program based on certain conditions that are only known at run time.

If Statement:

The control of the program depends upon the condition result that is a Boolean value, either true or false. The types of if statement are if statement,if-else statement,else-if statement and Nested if-statement.

Syntax:

if(< condition>) {
//block of code
}

Switch Statement:

The switch statement helps us to check the variable for the range of values defined for multiple case statements.

Syntax:

switch < variable> {
Case < value1>:
// statements
Case < value n>:
// statements
Default:
// statements
}

Iteration Statements or Loop Statements:

Iteration Statements or loop statements are used to execute the set of instructions in a repeated order.

For loop:

It enables us to initialize the loop variable, check the condition, and increment/decrement in a line of code.

Syntax:

for(< initialization>, < condition>, < increment/decrement>) {
//statements
}

For-each loop:

Java provides a loop to traverse the data structures like array or collection.

Syntax:

for(type var : collection){
//statements
}

while loop:

The while loop is used to iterate over the number of statements multiple times.

Syntax:

While(< condition>){
//statements
}

do-while loop:

The do-while loop executes the loop statement and then checks the condition at the end of the loop.

Syntax:

do
{
//statements
} while (< Condition>);

Jump Statements

Jump statements are used for transferring the control of the program to the specific statements given.

Break statement:

The Break statement is used to breaking the current flow of the program and transferring the control to the next statement outside the current flow. The Break statement is used for breaking the loop and in the switch statement.

Continue statement:

Continue statement does not break the loop, but it skips the specific part of the loop and jumps immediately to the next iteration of the loop.

Example No.1:

Com.knowledge2life class Condition { public static void main(String[] args) { String a = new String("Knowledge2life"); if (a.equals("Knowledge2life")) { System.out.println("Knowledge2life!"); } } }

OUTPUT:

Knowledge2life!

Example No.2:

Com.knowledge2life class Condition1 { public static void main(String[] args) { int a=20; int b=10; if (a==b) { System.out.println("A equal to B"); } else System.out.println("Knowledge2life!"); } }

OUTPUT:

Knowledge2life!