Day 4 : Conditional Statements in Java

Day 4 : Conditional Statements in Java

Conditional Statements :

Conditional statements are control flow statements that allow you to execute different blocks of code based on whether a specified condition evaluates to true or false. These statements help in making decisions within a program, enabling it to behave differently under different circumstances.

  • if statement
  • if-else statement
  • if-else-if ladder statement
  • Nested if statement
  • Switch Statement

if statement :

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax :

if(condition) {    
statement 1;  // executes when condition is true   
}            

Example :

public class IfExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 5
        // Check in if condition a is greater than b 
        if (a> b) {
            System.out.println("a is greater");  // Output : a is greater
        }
    }
}        

In this example :

  • Declared an integer variable a and initializes it with the value 10.
  • Declared an integer variable b and initializes it with the value 5. Note the semicolon at the end of this statement.
  • In if condition, Checks if the value of a (which is 10) is greater than the value of b (which is 5).
  • If the condition a > b evaluates to true, it executes the block of code inside the { }, in this example prints "a is greater".
  • Since a (10) is indeed greater than b (5), the condition a > b is true, and therefore, a is greater will be printed as output.

if-else statement :

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax :

if(condition) {    
statement 1;  // executes when condition is true   
}  
else{  
statement 2;  // executes when condition is false   
}          

Example :

public class ElseIfExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 25;
        // Check in if condition a is greater than b 
        if (a> b) {
            System.out.println("a is greater");  // Output : a is greater
        }
        else {
            System.out.println("b is greater");
        } 
    }
}        

In this example :

  • Declared an integer variable a and initializes it with the value 10.
  • Declared an integer variable b and initializes it with the value 25. Note the semicolon at the end of this statement.
  • Checks in if condition, if the value of a (which is 10) is greater than the value of b (which is 25).
  • Since a is not greater than b, the condition a > b evaluates to false.
  • Therefore, the block of code inside the else { } is executed, which prints "b is greater" to the console.
  • Since a (10) is not greater than b (25), the else block executes, and thus b is greater will be printed as output.

if-else-if ladder :

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.

Syntax :

if(condition 1) {    
statement 1;  // executes when condition 1 is true   
}  
else if(condition 2) {  
statement 2;  // executes when condition 2 is true   
}  
else {  
statement 2;  // executes when all the conditions are false   
}          

Example :

public class IfElseIfLadderExample {
    public static void main(String[] args) {
        int num1 = 20;
        int num2 = 50;
        int num3 = 25;
        int num4 = 30;
        if (num1 >= num2 && num1 >= num3 && num1 >= num4) {
            System.out.println("The largest number is : " + num1);
        } 
        else if (num2 >= num1 && num2 >= num3 && num2 >= num4) {
            System.out.println("The largest number is : " + num2);
        } 
        else if (num3 >= num1 && num3 >= num2 && num3 >= num4) {
            System.out.println("The largest number is : " + num3);
        } 
        else {
            System.out.println("The largest number is : " + num4);
        }
    }
}        

In this example :

  • Declared four integer variables num1, num2, num3, and num4 and initializes them with the values 20, 50, 25, and 30, respectively.
  • The if, else if, and else statements form an "if-else-if ladder".
  • Each if condition checks if one number is greater than or equal to the other three numbers (num1 >= num2 && num1 >= num3 && num1 >= num4).
  • If the condition is true, it prints that number as the largest.
  • If not, it moves to the next else if condition until the appropriate condition is met.
  • The else block handles the case where num4 is the largest among the four numbers.
  • In this example, num2 (50) is the largest among num1 (20), num2 (50), num3 (25), and num4 (30), so the output will be The largest number is : 50.

Nested if statement :

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

Syntax :

if(condition 1) {    
statement 1; // executes when condition 1 is true   
if(condition 2) {  
statement 2; // executes when condition 2 is true   
}  
else{  
statement 2; // executes when condition 2 is false   
}  
}          

Example :

public class LargestThreeNumbers {
    public static void main(String[] args) {
        int num1 = 20;
        int num2 = 50;
        int num3 = 25;
        if (num1 >= num2) {
            if (num1 >= num3) {
                System.out.println("The largest number is : " + num1);
            } 
           else {
                System.out.println("The largest number is : " + num3);
            }
        } 
        else {
            if (num2 >= num3) {
                System.out.println("The largest number is : " + num2);
            } 
            else {
                System.out.println("The largest number is : " + num3);
            }
        }
    }
}        

In this example :

  • Declared three integer variables num1, num2, and num3 and initializes them with the values 20, 50, and 25, respectively.
  • The outer if statements compare num1 with num2.
  • Depending on whether num1 is greater than or equal to num2, it further compares num1 with num3 or num2 with num3 inside nested if-else statements.
  • This nested structure ensures that we find the largest number among the three variables.
  • In this example, num2 (50) is the largest among num1 (20), num2 (50), and num3 (25), so the output will be The largest number is : 50.

Switch Statement :

Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.

Here are some key points to keep in mind about the switch statement in Java :

  • The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
  • Cases cannot be duplicate
  • Default statement is executed when any of the case doesn't match the value of expression. It is optional.
  • Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed.
  • While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.

Syntax :

switch (expression){  
    case value1:  
     statement1;  
     break;  
    case value2:  
     statement2;  
     break;  
    .  
    .  
    .  
    case valueN:  
     statementN;  
     break;  
    default:  
     default statement;  
}          

Example :

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;
        String dayName;
        switch (day) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
                break;
        }

        System.out.println("Day " + day + " is " + dayName);
    }
}        

In this example :

  • Initialized an integer variable day with the value 3, representing Wednesday.
  • The switch statement evaluates the value of day.
  • Depending on the value of day, it assigns the corresponding dayName using case labels.
  • Each case label represents a day of the week from 1 (Monday) to 7 (Sunday).
  • The default case handles any other values that do not match the specified cases, assigning dayName as "Invalid day".
  • Each case block ends with a break statement, which exits the switch statement after executing the corresponding case.
  • This prevents execution from "falling through" to subsequent cases, ensuring that only the matching case block is executed.
  • Finally, the program prints the day value along with the corresponding dayName using System.out.println().
  • If day is 3, the output will be Day 3 is Wednesday.

要查看或添加评论,请登录

POOJAASHREE P V的更多文章

  • Day 13 : File Handling in Java

    Day 13 : File Handling in Java

    File Class : The File class of the java.io package is used to perform various operations on files and directories.

  • Day 12 : Scanner Class in Java

    Day 12 : Scanner Class in Java

    Scanner Class : Scanner class in Java is found in the java.util package.

  • Day 11 : Exception Handling in Java

    Day 11 : Exception Handling in Java

    Exception : An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at…

  • Day 10 : Arrays in Java

    Day 10 : Arrays in Java

    Arrays : Array is an object which contains elements of a similar data type. The elements of an array are stored in a…

  • Day 9 : Date and Time in Java

    Day 9 : Date and Time in Java

    Date and Time : In Java, managing date and time involves several classes from the package, introduced in Java 8. The…

  • Day 8 : String, String Methods, String Builder and String Buffer in Java

    Day 8 : String, String Methods, String Builder and String Buffer in Java

    String : String is an object that represents a sequence of characters. The java.

  • Day 7 : Math Class and Math Methods in Java

    Day 7 : Math Class and Math Methods in Java

    Math Class : Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos()…

  • Day 6 : Methods in Java

    Day 6 : Methods in Java

    Method : A method is a block of code or collection of statements or a set of code grouped together to perform a certain…

  • Day 5 : Looping Statements in Java

    Day 5 : Looping Statements in Java

    Looping Statements : Looping statements are used to execute a block of code repeatedly based on certain conditions…

    1 条评论
  • Day 3 : Variables, Data Types and Operators

    Day 3 : Variables, Data Types and Operators

    Variables : A variable is a container which holds the value while the Java program is executed. A variable is assigned…

社区洞察

其他会员也浏览了