The if statement is known as a single selection structure since we have only a single statement that is either executed or not.
syntax:
if(condition)
{
statement}
else
{
statement
}
when the condition is true it is execute the if block, when the condition is false it will go to the else block..
EX:-Snippet for the simple conditional statement which uses if condition
public static void main(String[] args) {
int a=10,b=20;
if(a>b)
{
System.out.println(a);
}
else
System.out.println(b);
}
}
Nested if-statement
A nested if is an if statement that is the target to another if or else statement.
A nested if is an if statement that is the target to another if or else statement.
Syntax:
if (condition)
{
statement
else
if(condition)
statement
else
if(condition)
.
.
.
.
.
else
statement
}
Example
----
----
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=10, b=20, c=30 ;
if(a > b)
{
if(a > c)
{
System.out.println("the biggest value="+ a);
}
else
System.out.println("the biggest value="+ c) ;
}
else
{
if(c > b)
System.out.println("the biggest value="+c);
else
System.out.println("the biggest value="+b);
}
}
}
The switch control structure however cannot be used in the situations where the condition needs to contain relational operators like greater than, less than and so on. The switch structure can only be used to check for equality. Given below is the syntax of the switch structure in Java.
switch ( expression )
{
case value1 :
// code
break;
case value2:
// code
break;
...
...
case valueN:
// code
break;
...
...
default:
// code
break;
}
{
case value1 :
// code
break;
case value2:
// code
break;
...
...
case valueN:
// code
break;
...
...
default:
// code
break;
}
The expression should evaluate to one of the following types: byte, short, int, char, String. This value is compared with each of the case values ( value1, value2,... valueN). When a match is found, the statements under that particular case label are executed. Strings are checked for equality by invoking the equals() method and not by using the == operator which is the used for the other data types.
Example---
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter number");
int day = s.nextInt(); // s is a Scanner object connected to System.in
String str; // stores the day in words
switch(day)
{
case 1:
str="Sunday";
break;
case 2:
str="Monday";
break;
case 3:
str="Tuesday";
break;
case 4:
str="Wednesday";
break;
case 5:
str="Thursday";
break;
case 6:
str="Friday";
break;
case 7:
str="Saturday";
break;
default:
str=" Invalid day";
}
System.out.println(str);
}
}