Conditional Statements:
==> Conditional statements, like the if-else statement in Java, control program flow based on conditions.
==> The if-else syntax consists of an initial condition followed by code blocks for true and false outcomes.
==> It enables executing different code paths depending on whether a condition evaluates to true or false.
Types of Decision-Making Statements:
- if statement
- if-else statement
- if-else-if statement
- nested-if statement
- switch statement
If Statement:
==> If a certain condition is true then a block of statements is executed otherwise not.
Example program:
package day1if;
public class Main {
public static void main(String[] args)
{
// TODO Auto-generated method stub
int bat=500;
if(bat >=500)
{
System.out.println("go to play");
System.out.println("dont play");
}
}
}
Output:
go to play
dont play
If else statement:
==> The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Example program:
package day1if;
public class Main1 {
public static void main(String []args)
{
int bat=500;
if(bat>600)
{
System.out.println("go to play");
}
else{
System.out.println("don't play");
}
}
}
Output:
don't play
If-else if statement:
==> The if-else if statement allows for multiple conditions to be checked in sequance if the if condition is false
==> The program checks the next else if condition,and so on
==> In else if statement,the condition are checked from top down if the first block returns true,the second,third block will not be checked
==> But if the first block return false,the second block will be checked
==> This condition checking continues untill a block returns a true outcome
Example program:
package day1if;
public class IfElseIfStatement
{
public static void main(String [] args)
{
int num1 = 20, num2 = 20;
if(num1 > num2)
{
System.out.println("num1 is greater than num2");
}
else if(num1 == num2)
{
System.out.println("num1 is equal to num2");
}
else
{
System.out.println("num1 is less than num2");
}
}
}
Output:
num1 is equal to num2
Nested if ststement:
==> Nested if in Java refers to having one if statement inside another if statement.
==> If the outer condition is true the inner conditions are checked and executed accordingly.
==> Nested if condition comes under decision-making statement in Java, enabling multiple branches of execution
Example Program:
package javaprogram;
public class Nested {
public static void main(String args[])
{
int a = 10;
int b = 20;
// Outer if condition
if (a == 10)
{
System.out.println("Geeks");
// Inner if condition
if (b < 20)
{
System.out.println("GeeksforGeeks");
}
else
{
System.out.println("geek for geek");
if (b <= 20)
{
System.out.println("for");
}
}
}
}
}
Output:
Geeks
geek for geek
for
Top comments (0)