Java Conditional Statements

Conditional statements are used to evaluate one or more logical conditions along with a block of statements to be executed if the condition return true and optionally another block of statements to be executed if the logical condition return false. There are following conditional statements in java.

If Statement

The if statement is used to execute a block of code only if the applied condition (Boolean expression) return true.

Syntax:

if (condition) {

statements to be executed

}

The default and break statements are optional. Also there can be any number of case blocks in switch statement.

If – Else statement

The if – else statement consist of one if statement with a block of code to be executed if the condition return true and another block of code under else clause which is executed if the condition return false.

Syntax:

if (condition) {

statements to be executed if condition return true

} else {

statements to be executed if condition return false

}

If- Else – If statement

This is a nested if – else statement. It consist of multiple if conditions and an else statement. Each if condition has a block of code which is execute when the condition return true.

Syntax:

if (condition 1) {

statements to be executed if condition 1 return true

} else if(condition 2){

statements to be executed if condition 2 return true

} else {

statements to be executed if all condition return false

}

Switch Statement

The switch statement is used to test a variable for equality against a list of values. The switch statement is enclosed in a switch block and one or more case and/or default labels. The switch statement evaluate each case and execute the appropriate case block.

Syntax:

switch(expression){

case value1 :

statements to be executed

break;

case value2 :

statements to be executed

break;

case value3 :

statements to be executed

break;

default :

statements to be executed

}

The default and break statements are optional also there can be any number of case blocks in switch statement.

Leave a Reply

Your email address will not be published. Required fields are marked *