The statement that programming language used to decide , which code has to be run when the condition is met.
There are 4 types of Conditional Statements , that are
1) if statement
2) if else statement
3) Nested if statement
4) Switch statement
if statement :
The if statement checks the condition and if the result is true , it runs the code.
Example :
public class Ifstatement
{
public static void main(String[] args)
{
int i = 2;
if (i%2 == 0)
System.out.println("i is an even number");
}
}
if else statement :
If the condition is true , then it will execute the "if statement" , else it will execute the "else statement".
Example :
public class Ifelsestatement
{
public static void main(String[] args)
{
int i = 5;
if (i%2==0)
System.out.println(i+" is an even number.");
else
System.out.println(i+" is an odd number.");
}
}
Nested if statement :
There will be many conditions in "nested if statement", where any condition can be satisfied.
Example :
public class Ifstatementnested
{
public static void main(String[] args)
{
int i = 1;
if (i > 0)
System.out.println(i+" is Positive.");
else
if (i < 0)
System.out.println (i+" is Negative.");
else
System.out.println (i+" is Zero.");
}
}
switch statement :
The switch statement takes a variable and then has a list of cases or actions to perform for each value that the variable obtains.It uses the word default to perform actions in which the conditions are not met and it uses the word break to stop performing actions.
Example :
public class Switchstatement
{
public static void main(String[] args)
{
int i = 5;
switch(i)
{
case 1:
System.out.println ("i is 1");
break;
case 2:
System.out.println ("i is 2");
break;
case 3:
System.out.println ("i is 3");
break;
case 4
System.out.println(“i is 4”);
break;
case 5:
System.out.println(“i is 5”);
break;
default:
System.out.println("Invalid value");
}
}
}
Thanks ,
A M Balaji