Selection Statements in Java (2)
Selection Statements in Java (2)
• Sequential Construct.
• Selection/Decision Making/Conditional/Branching Construct.
→ if, if else, if else if, nested if and switch statements
• Looping/Iterative Construct.
→ for, while, do..while loops.
if statement in java
Syntax:-
if(test expression) { true block statements;}
Next statement;
Example:-
if(x==5) {System.out.println(“X value is 5”);}
System.out.println(“Hello”);
if else statement in java
Syntax:-
if(test expression) { if block statements;}
else
{ else block statements;}
Next statement;
Example:-
if(x%2==o) {System.out.println(“Even”);}
else {System.out.println(“Odd”);}
System.out.println(“Hello”);
Ternary operator in java→ ?:
Example:-
max = a>b ? a :b;
Ternary operator in java→ ?:
Next statement;
Nested if
Syntax:-
if(condition1)
{
if(condition2) {statement block;}
}
else
{
if(condition3) { statement block;}
}
Next statement;
Dangling else problem
It is the ambiguity that arises in the nested if statement , when the number of if
clause is more than the number of else clause. Java matches the else with the
nearest if clause. To solve this problem, curly brackets can be used according to the
user’s requirement.
For example:-
if(ch>=‘A’)
if(ch>=‘A’) {
if (ch<=‘Z’) if (ch<=‘Z’)
System.out.println(“Upper case”);
System.out.println(“Upper case”); }
else else
System.out.println(“Others”);
System.out.println(“Others”);
switch statement in java
It is the multi-way branching statement in java where the compiler tests the expression
against the list of values and executes the corresponding matching case. If there is no
matching case, the default is executed.
Syntax:-
switch(expression)
{ switch(Day)
case value1: statements; {
break; case 1: System.out.println(“Sunday”);
case value2:statements; break;
break; case 2: System.out.println(“Monday”);
case valuen:statements;
break;
break;
:
:
: :
default: statements default: System.out.println(“Invalid data”);
} }
switch statement in java
• There can be one or N number of case values for a switch expression.
• It checks only for the equality condition.
• The case value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-
time error.
• The Java switch expression must be of byte, short, int, long, char and String.
• default label is optional.
• break is optional in each case.