In Java, decision and control statements allow you to select and execute specific blocks of the code while skipping other sections or statements.
The if
statement consists of a condition followed by one or more statements.
The syntax of an if
statement is as follows:
if(condition) { //Statements will execute if the condition is true }
An example of this is as follows:
package MyFirstPackage; public class IfCondition { public static void main(String[] args) { int empSal = 20000; if (empSal >= 10000) { System.out.println("he is a manager...!"); } else { System.out.println("he is NOT a manager...!"); } } }
The output of the preceding code is as follows:
he is a manager...!
The if
statement can be followed by an optional else
statement, which executes when the condition is false
.
The syntax of an if...else
statement is:
if(condition){ //Executes when the condition is true }else{ //Executes when the condition is false }
The if statement can be followed by an optional else if...else
statement, which is very useful to test various conditions using single if...else if
statement.
The syntax of an if...else
statement is:
if(condition 1){ //Executes when the condition 1 is true }else if(condition 2){ //Executes when the condition 2 is true }else if(condition 3){ //Executes when the condition 3 is true }else { //Executes when the one of the above condition is true. }
It is always legal to nest if..else
statements. When using if...else if... else...
statements, there are a few points to keep in mind:
An
if
statement can have zero or oneelse
statement and it must come after anyelse if
statementsAn
if
statement can have zero to manyelse if
statements and they must come before theelse
statementOnce an
else if
statement succeeds, none of the remainingelse if
statements orelse
statements will be tested
The syntax for a nested if...else
statement is as follows:
if(condition 1){ //Executes when the condition 1 is true if(condition 2){ //Executes when the condition 2 is true } }
A switch
statement allows a variable to be tested for equality against a list of values. Each value is called a case
, and the variable being switched on is checked for each case
.
The syntax of a switch statement is:
switch(expression){ case value : //Statements break; //optional case value : //Statements break; //optional //You can have any number of case statements. default : //Optional //Statements }