Branching Statements(if ,If-else,nested if,if else if )
Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
- If
- If-else
- nested-if
- if -else-if
- switch case
- jump-brake,continue, return
Examples:-
class Example
{
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.println("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}else
{
System.out.println("odd number");
}
}
}
Syntax:
if (condition 1)
{
if (condition 2)
{
Statements;
}
}
Flowchart:-
Example:-
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
if (i < 15)
{
System.out.println("i is smaller than 15");
if (i < 12)
{
System.out.println("i is smaller than 12 too");
}else
{
System.out.println("i is greater than 15");
}
}
}
}
Syntax:-
if (condition)
{
statement;
}else if (condition)
{
statement;
.
.
}else
{
statement;
class Demo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Comments
Post a Comment