Understanding Switch Case in Java
The switch-case statement is a powerful feature in Java used for decision-making. It provides a concise way to evaluate a single expression against multiple possible values and execute different blocks of code based on the match. This is particularly useful when you have a series of conditions to check against the same variable.
case value1:
// code block
break;
case value2:
// code block break; // more cases can be added as needed default: // code block to be executed if no case matches }
Here's a breakdown:
i.'switch' is followed by an expression (often a variable or a method call).
ii.'case' labels specify the values to match against the expression.
iii.If the expression matches a 'case' label, the corresponding block of code executes. The break statement exits the switch block.
iv.If none of the 'case' labels match the expression, the 'default' block (if present) executes.
Question-1: Using Switch case, write a program that allows to accept any values from 1 to 7 and displays the weekdays corresponding to the number entered from the key board.
OUTPUT:
Enter the choice :
3
wednesday
Question-2:Write a program using switch case to find the volume of cube, a sphere and a cuboid. For an incorrect choice an appropriate error message should be displayed.
1. Volume of a cube = s * s * s.
2. Volume of a sphere = 4/3 * 𝜋 * r * r * r .
3. Volume of a cuboid = l * b * h.
OUTPUT:
1.Volume of a cube :
2.Volume of a sphere :
3.Volume of a cuboid :
Enter your choice :
2
Enter r:
5
Volume of a sphere=3666.0
1. Write a menu driven program to calculate:
i. Area of a circle = 𝜋𝑟2.
ii. Area of a square = side * side.
iii. Area of a rectangle = length * breadth.
Enter ‘c’ to calculate area of circle ,‘s’ to calculate area of square and ‘r’ to calculate area of rectangle.
The switch-case statement in Java provides a concise way to evaluate a single expression against multiple possible values and execute different blocks of code based on the match. It enhances code readability and maintainability by simplifying complex conditional branching. However, it's important to note that switch-case statements are limited to certain data types (such as integers, characters, and enums) and cannot be used with floating-point numbers or strings.