Published July 03, 2024

Conditional Statement In Java

Conditional Statements are used to make decisions in a program based on certain conditions. They allow the program to execute different code blocks depending on whether a condition evaluates to true or false.

image

Conditional Statements are used to make decisions in a program based on certain conditions. They allow the program to execute different code blocks depending on whether a condition evaluates to true or false. It plays a key role in programming logic by enabling the implementation of branching behavior, where the program can choose between alternative paths of execution based on specific conditions.

It plays a key role in programming logic by enabling the implementation of branching behavior, where the program can choose between alternative paths of execution based on specific conditions.

if Statement:


It evaluates a condition and executes a block of code if the condition is true.
int x = 10;
if (x > 5) {
    System.out.println("x is greater than 5");
}

if-else Statement:
 


The if-else statement evaluates a condition and executes one block of code if the condition is true and another block if the condition is false.
Example: Check whether x is greater than 5.
int x = 10;
if (x > 5) {
    System.out.println("x is greater than 5");
} else {
    System.out.println("x is not greater than 5");
}

else-if ladder:
 


The else-if ladder allows checking multiple conditions sequentially until one of them evaluates to true. It is useful when there are more than two possible outcomes.
Example: Check whether x is greater than or lesser than or equals to 15.
int x = 10;
if (x > 10) {
    System.out.println("x is greater than 15");
} else if (x < 15) {
    System.out.println("x is less than 15");
} else {
    System.out.println("x is equal to 15");
}

Nested if Statements:
 


Nested if statements allow placing one if statement inside another if statement. It is useful when there is a need to check multiple conditions in a hierarchical manner.
Example: Check whether x is between the range of 5 to 15 or not.
int x = 10;
if (x > 5) {
    if (x < 15) {
        System.out.println("x is between 5 and 15");
    }
}

Switch Statement:
 


It evaluates an expression and executes code blocks based on matching case labels. It provides an alternative to if-else ladder when there are multiple cases to be checked against the same value.
Example: Print day name of the weeek after receiveing any number between 1 to 7 otherwise errror message.
int day = 3;
switch (day) {
    case 1:
        System.out.println("Sunday");
        break;
    case 2:
        System.out.println("Monday");
        break;
    case 3:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Invalid day");
}

Multiple choice Questions on java conditional statements:

Q1. What is the purpose of conditional statements in Java?
A) To repeat a block of code
B) To execute a block of code only if a condition is true
C) To define a class
D) To declare variables

Q2. What will happen if the condition in an if statement evaluates to false?
A) The block of code inside the if statement will be skipped
B) The block of code inside the if statement will be executed
C) An error will occur
D) The program will terminate

Q3. Which of the following is NOT a valid comparison operator in Java?
A) ==
B) =
C) !=
D) >

Q4. What does the "else" keyword do in Java?
A) It starts a loop
B) It declares a new variable
C) It defines an alternative block of code to execute if the condition of the if statement is false
D) It throws an exception

Q5. What will be the output of the following code?
int num = 5;
if (num > 18) {
    System.out.println("num is greater than 18");
} else {
    System.out.println("num is less than or equal to 18");
}
A) num is greater than 18
B) num is less than 18
C) num is less than or equal to 18
D) num is greater than or equal to 18

Q6. In Java, what is the purpose of the "else if" statement?
A) An alternative block of code to execute, "if" statement is false
B) To define a new variable
C) To create a loop
D) To declare a method

Q7. What will be the output of the following code?
int num = 10;
if (num < 20) {
    System.out.println("num is less than 20");
}
A) num is less than 20
B) num is greater than 20
C) num is equal to 20
D) There will be no output

Q8. Which of the following is true about the "switch" statement in Java?
A) It can be used to compare integers only
B) It is similar to a series of "if" statements
C) It cannot have a default case
D) It can only have one case block

Q9. In a switch statement, which keyword is used to define the default case?
A) default
B) break
C) case
D) else

Q10. What will happen if a "break" statement is omitted in a switch case block?
A) compilation error
B) Cause a runtime error
C) Skip the current case and execute the next case
D) Cause an infinite loop

Q11. Which of the following is NOT a logical operator in Java?
A) &&
B) ||
C) !
D) ++

Q12. What will be the output of the following code snippet?
int x = 5;
int y = 10;
if (x > 3 && y < 15) {
    System.out.println("Both conditions are true");
} else {
    System.out.println("At least one condition is false");
}
A) Both conditions are true
B) At least one condition is false
C) Both conditions are false
D) There will be a compilation error

Q13. What will be the output of the following code snippet?
int x = 5;
int y = 10;
if (x > 3 || y > 15) {
    System.out.println("At least one condition is true");
} else {
    System.out.println("Both conditions are false");
}
A) At least one condition is true
B) Both conditions are false
C) Both conditions are true
D) There will be a compilation error

Q14. Which of the following is true about the ternary operator in Java?
A) It can only be used with boolean expressions
B) It is equivalent to an if-else statement
C) It cannot be nested
D) It is represented by the symbol "?"

Q15. What will be the output of the following code snippet?
int x = 5;
int result = (x > 10) ? 10 : (x < 0) ? 20 : 30;
System.out.println(result);
A) 10
B) 20
C) 30
D) 5

Q16. In Java, what does the expression "x > y ? x : y" represent?
A) The maximum of x and y
B) The minimum of x and y
C) The sum of x and y
D) The difference between x and y

Q17. What will be the output of the following code snippet?
int x = 5;
int y = 10;
if (x > y) {
    System.out.println("x is greater than y");
} else if (x < y) {
    System.out.println("x is less than y");
} else {
    System.out.println("x is equal to y");
}
A) x is greater than y
B) x is less than y
C) x is equal to y
D) There will be no output

Q18. Which of the following statements is true about nested if-else statements?
A) They cannot be used in Java
B) They can only have one else block
C) They can lead to complex code and reduced readability
D) They are always more efficient than switch statements

Q19. In Java, what will happen if multiple conditions in a switch statement match?
A) compilation error
B) runtime error
C) execute the first matching case block and exit the switch statement
D) execute all matching case blocks

Q20. Which of the following is true about the "default" case in a switch statement?
A) It must be placed before all other case blocks
B) executed if none of the other case blocks match the value of the expression
C) It is optional and can be omitted
D) It is mandatory in every switch statement


Q21. In Java, what will happen if no case matches the value of the expression in a switch statement and there is no default case?
A) Compilation error
B) Cause a runtime error
C) Execute the first case block
D) Exit the switch statement without executing any case blocks

Multiple choice Question's Answer:

Q1. Correct Answer: B) To execute a block of code only if a condition is true
Explanation: Conditional statements in Java allow you to control the flow of your program by executing certain blocks of code based on whether certain conditions are met.

Q2. Correct Answer: A) The block of code inside the if statement will be skipped
Explanation: If the condition in an if statement evaluates to false, the block of code inside the if statement will not be executed.

Q3. Correct Answer: B) =
Explanation: "=" is the assignment operator in Java, not a comparison operator. Comparison operators include "==", "!=", ">", "<", ">=", and "<=".

Q4. Correct Answer: C) It defines an alternative block of code to execute if the condition of the if statement is falseExplanation: The "else" keyword allows you to specify a block of code to be executed if the condition of the preceding "if" statement is false.

Q5. Correct Answer: C) x is less than or equal to 10
Explanation: Since the value of x is 5, the condition (x > 10) evaluates to false, so the code inside the "else" block will be executed.

Q6. Correct Answer: A) An alternative block of code to execute, "if" statement is false
Explanation: The "else if" statement allows you to specify additional conditions to be checked if the condition of the preceding "if" statement is false.

Q7. Correct Answer: A) x is less than 20
Explanation: Since the condition (x < 20) evaluates to true, the code inside the if statement will be executed, resulting in the output "x is less than 20".

Q8. Correct Answer: B) It is similar to a series of "if" statements
Explanation: The "switch" statement in Java allows you to select one of many code blocks to be executed based on the value of an expression. It is similar to a series of "if" statements.

Q9. Correct Answer: A) default
Explanation: The "default" keyword is used to define the default case in a switch statement. This case is executed if none of the other cases match the value of the expression.

Q10. Correct Answer: C) It will skip the current case and execute the next case
Explanation: If a "break" statement is omitted in a switch case block, execution will continue to the next case block, resulting in the unintended behavior of executing multiple case blocks.

Q11. Correct Answer: D) ++
Explanation: "++" is the increment operator in Java, not a logical operator. Logical operators include "&&" (logical AND), "||" (logical OR), and "!" (logical NOT).

Q12. Correct Answer: A) Both conditions are true
Explanation: Both conditions (x > 3) and (y < 15) evaluate to true, so the code inside the if statement will be executed.

Q13. Correct Answer: A) At least one condition is true
Explanation: The condition (x > 3 || y > 15) evaluates to true because at least one of the conditions (x > 3) or (y > 15) is true.

Q14. Correct Answer: B) It is equivalent to an if-else statement
Explanation: The ternary operator (?:) in Java provides a shorter syntax for expressing conditional statements, similar to an if-else statement.

Q15. Correct Answer: C) 30
Explanation: Since the value of "x" (5) is not greater than 10 and not less than 0, the expression evaluates to 30.

Q16. Correct Answer: A) The maximum of x and y
Explanation: This expression returns the value of "x" if "x" is greater than "y", otherwise it returns the value of "y", effectively representing the maximum of the two values.

Q17. Correct Answer: B) x is less than y
Explanation: Since x (5) is less than y (10), the output will be "x is less than y".

Q18. Correct Answer: C) They can lead to complex code and reduced readability
Explanation: While nested if-else statements are valid in Java, they can make the code more complex and harder to read, especially if there are multiple levels of nesting.

Q19. Correct Answer: C) execute the first matching case block and exit the switch statement
Explanation: In a switch statement, if multiple conditions match, only the first matching case block will be executed, and then the switch statement will exit.

Q20. Correct Answer: B) executed if none of the other case blocks match the value of the expression
Explanation: The "default" case in a switch statement is optional and is executed if none of the other case blocks match the value of the expression.

Q21. Correct Answer: D) It will exit the switch statement without executing any case blocks
Explanation: If no case matches the value of the expression in a switch statement and there is no default case, the switch statement will simply exit without executing any case blocks.

Coding Questions based on conditional statements:

Use Case 1:
Radha and Pranali are sisters,print the name of elder sister or both are twins afer getting required information from user.

Use Case 2:
Make Insurance Calculator which calculate annual charge per person according to
following age group:
age 0-15  2500
age 16-25  3500
age 26-40  4000
age 41-50  4500
age 51-70  5500
discount could be calculated based on age:
age 0-15  2500  20%
age 16-25  3500 15%
age 26-40  4000  10%

Switch Case,
Use Case 1:

Write a program to get any two numbers and any one of the following:
+ - * / %

Use Case 2:
Find the type of triangle after getting required inputs:
Output could be on of following:
Equilateral: A triangle with 3 sides of equal length.
Isosceles: A triangle with 2 sides of equal length.
Scalene: A triangle with 3 sides of differing lengths.
Not A Triangle: The given values of A, B, and C don't form a triangle.


Use Case3: Based on given data you are required to write application that produce output given below:
Toppings table:
+--------------+------+
\| topping_name \| cost \|
+--------------+------+
\| Pepperoni    \| 0.50 \|
\| Sausage      \| 0.70 \|
\| Chicken      \| 0.55 \|
\| Extra Cheese \| 0.40 \|
+--------------+------+
Output: 
+--------------------------------+------------+
\| pizza                          \| total_cost \| 
+--------------------------------+------------+
\| Chicken,Pepperoni,Sausage      \| 1.75       \|  
\| Chicken,Extra Cheese,Sausage   \| 1.65       \|
\| Extra Cheese,Pepperoni,Sausage \| 1.60       \|
\| Chicken,Extra Cheese,Pepperoni \| 1.45       \| 
+--------------------------------+------------+
Solution:
package com.gni;
import java.util.Scanner;

public class Pizza {
    public static void main(String[] args) {
        double totalCost=0;
        int choice=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter type of pizza:1. Basic 2.Super:");
        while(true) {
            System.out.println("Enter type of pizza:1. Basic 2.Super:");
            choice = sc.nextInt();
            if(choice==1 || choice==2){
                if(choice==1){
                    totalCost+=160;
                    break;
                }
                if(choice==2){
                    totalCost+=250;
                    break;
                }
            }
        }

        System.out.println("Pepperoni 0 for no 1 for yes ");
        choice=sc.nextInt();
        if(choice==1){
            totalCost+=0.50;
        }
        System.out.println("Sausage  0 for no 1 for yes " );
        choice=sc.nextInt();
        if(choice==1){
            totalCost+=0.70;
        }
        System.out.println("Chicken   0 for no 1 for yes ");
        choice=sc.nextInt();
        if(choice==1){
            totalCost+=0.55;
        }
        System.out.println("Extra Cheese  0 for no 1 for yes ");
        choice=sc.nextInt();
        if(choice==1){
            totalCost+=0.40;
        }
        System.out.println("Total cost of pizza:"+totalCost);
    }
}

Use Case4: 
Ram is an engineer having assigned tast to run a tomcat server and note how many total minutes server runs in a whole day.
You are required to record number of minutes each day server runs during last 10 days.
Calculate total number of hours, minutes the server run.
Solution:
---------
package com.gni;
import java.util.Scanner;
public class TimeCalculator {
    public static void main(String[] args) {
        int totalMinutes=0;
        int totalHours=0;
        int totalDays=0;
        Scanner sc=new Scanner(System.in);
        for(int i=1;i<=10;i++){
            System.out.println("Enter value for day"+i+":");
            totalMinutes +=sc.nextInt();
        }
        if(totalMinutes>=(24*60)){//1570=1+2+10
            totalDays+=totalMinutes/(24*60);
            totalMinutes=totalMinutes%(24*60);
        }
        if(totalMinutes>=60){
            totalHours+=totalMinutes/60;
            totalMinutes=totalMinutes%60;
        }
        System.out.println("Total number of days:"+totalDays);
        System.out.println("Total number of hours:"+totalHours);
        System.out.println("Total number of minutes:"+totalMinutes);
    }
}


Use Case5: 
You are required to create an application that received any two lenghts in meters inches centimeters. Once you received, you need to add both values  into third length and display.

Download Lecture Pdf..

Reviews

image
Anu Priya
April 23, 2024

Sir, you also provide online course and when will you upload its notes sir?

image
Nitesh Singh
April 23, 2024

Sir I want to do full stack developer course

Leave a Comment