Lesson 4: Ternary Operator and Switch Statement
Understanding ternary operator and multi-way selection in Java
Ternary (Conditional) Operator
Syntax of the ternary conditional operator:
boolean-expression ? expression1 : expression2
If boolean-expression evaluates to true, the result is expression1; otherwise, the result is expression2.
Example 1: Finding the maximum of two numbers
max = (num1 > num2) ? num1 : num2;
Example 2: Checking if a number is even or odd
System.out.print((numb % 2 == 0) ? "an even number" : "not an even number");
Note: The ternary operator allows you to write shorter and more concise code compared to traditional if-else statements.
Switch Statement
Important: The switch statement allows you to select one action from multiple possibilities based on the value of an expression. It is an alternative to multiple nested if-else constructs, especially useful when you need to check many conditions.
Advantages of Switch Statement
- ▶ Clear structure and code readability
- ▶ Easy to extend with additional cases
- ▶ Fast processing of large condition lists due to compiler optimization
Basic Syntax
Basic form:
switch (variable_or_expression) {
case value1:
// Actions for case 1
break;
case value2:
// Actions for case 2
break;
default:
// Default action if no case matches
}
Important Notes:
-
▶
The
defaultblock executes when none of the other blocks match. -
▶
The
breakkeyword causes control to jump to the end of the switch after processing the block. If you omitbreak, execution will continue to the next case (fall-through).
Examples
Example with integer:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Unknown Day");
}
}
}
Result: Wednesday
Example with String (Java 7+):
public class StringSwitchExample {
public static void main(String[] args) {
String color = "green";
switch(color.toLowerCase()) { // Convert to lowercase for case-insensitive comparison
case "red":
System.out.println("Red");
break;
case "blue":
System.out.println("Blue");
break;
case "green":
System.out.println("Green");
break;
default:
System.out.println("Unknown color");
}
}
}
Result: Green
Example with Enum:
public enum Seasons {
WINTER,
SPRING,
SUMMER,
AUTUMN
}
public class EnumSwitchExample {
public static void main(String[] args) {
Seasons season = Seasons.SUMMER;
switch(season) {
case WINTER:
System.out.println("It is winter.");
break;
case SPRING:
System.out.println("It is spring.");
break;
case SUMMER:
System.out.println("It is summer.");
break;
case AUTUMN:
System.out.println("It is autumn.");
break;
}
}
}
Result: It is summer.
Tasks: Ternary Operator
Task 1: Age-Based Ticket Price with Ternary Operator
Objective: Create a program to input age and output ticket price. Rewrite the following if-else statement using the ternary conditional operator.
Original if-else code:
if (ages >= 16) {
ticketPrice = 20;
} else {
ticketPrice = 10;
}
Expected Output:
Please enter your age 16 Price is 20
[File name and class name: L4Task1.java]
Task 2: Convert Ternary to If-Else
Objective: Create a program that rewrites the following ternary expressions using traditional if-else statements. First declare and initialize all necessary variables with appropriate values.
Ternary expressions to convert:
1. score = (x > 10) ? 3 * scale : 4 * scale;
2. tax = (income > 10000) ? income * 0.2 : income * 0.17 + 1000;
3. System.out.println((number % 3 == 0) ? i : j);
[File name and class name: L4Task2.java]
Laboratory Works: Switch Statement
Lab 1: Coffee Size Selection
Objective: Request user to input a number — coffee size (1=small, 2=medium, 3=large). Output the price (1 — 25 cents, 2 — 50 cents, 3 — 75 cents). Use switch statement. Replace "..." with the code where it's required.
[File name and class name: L4Lab1.java]
Expected Output:
Coffee sizes: 1=small, 2=medium, 3=large Please enter your selection: 2 The result: Please insert 25 cents +++ Coffee sizes: 1=small, 2=medium, 3=large Please enter your selection: 5 The result: Invalid selection. Please select 1, 2, or 3.
Algorithm:
- Within the folder 'java' create a new file named
L4Lab1.java. - In the very first line import the Scanner package:
import ...; - Add the class definition and main method:
public class L4Lab1 { public static void main(...) { } } - Place your cursor immediately after the open curly brace in the main method, then press enter to create a new line.
- Enter
println()method to explain coffee sizes and request user selection:System.out.println("Coffee sizes: 1=small 2=medium 3=large"); - Request user to input with
println()method:System.out.println("Please enter your selection:"); - Create Scanner object:
Scanner scanner = ...; - Assign the entered value to a string variable:
String str = ...; - Initialize a variable
pricewith value 0:int price = 0; - Create a switch-case statement to test the
strvariable:switch (str) { case "1": price += 25; break; case "2": price += 50; break; case "3": ...; ...; } - Add a default section to output a message for invalid input:
switch (str) { case "1": price += 25; break; case "2": price += 50; break; case "3": ...; ...; default: System.out.println("Invalid selection. Please select 1, 2, or 3."); break; } - Check the
pricevariable and output the price if valid:if (price != 0) { System.out.printf("Please insert %d cents.%n", price); } - Press F5 to run the program or use commands for terminal.
- Experiment with different values to see the output.
- Save the project and upload the file to the learning management system.
Lab 2: Month to Season Converter
Objective: Create a program that requests a month number from user and displays the corresponding season name. Use switch statement.
[File name and class name: L4Lab2.java]
Expected Output:
Please enter a month number 7 Summer +++ Please enter a month number 15 Incorrect month number!
Algorithm:
- Create a new Java file named
L4Lab2.java. - Import the Scanner class at the top of the file.
- Define the class
L4Lab2with a main method. - Inside the main method, create a Scanner object for user input.
- Prompt the user to enter a month number (1-12).
- Read the integer input from the user.
- Use a switch statement to determine the season based on the month number:
- ▶ Cases 12, 1, 2: "Winter"
- ▶ Cases 3, 4, 5: "Spring"
- ▶ Cases 6, 7, 8: "Summer"
- ▶ Cases 9, 10, 11: "Autumn"
- Add a default case to handle invalid month numbers (outside 1-12).
- Output the corresponding season name or error message.
- Close the Scanner object.
- Test the program with different month numbers to ensure correct season output.
Lab 3: Day of Week Message
Objective: Write a program that accepts a string representing a day of the week and outputs a corresponding message (Start of work week, Work day, End of work week soon, Weekend day). Use switch statement.
[File name and class name: L4Lab3.java]
Expected Output:
Enter day of the week (e.g., Monday): Monday Start of work week +++ Enter day of the week (e.g., Monday): Friday End of work week soon
Algorithm:
- Create a new Java file named
L4Lab3.java. - Import the Scanner class.
- Define the class
L4Lab3with a main method. - Create a Scanner object for user input.
- Prompt the user to enter a day of the week (e.g., Monday).
- Read the input string and convert it to lowercase using
toLowerCase()for case-insensitive comparison. - Use a switch statement to check the input day:
- ▶ Case "monday": "Start of work week"
- ▶ Case "friday": "End of work week soon"
- ▶ Cases "saturday", "sunday": "Weekend day"
- ▶ Default: "Work day"
- Output the corresponding message.
- Close the Scanner object.
- Test the program with different days of the week to verify correct message output.
Independent Work Tasks
Task 3: Importance Level
Objective: Implement a program that accepts a number from 1 to 10 inclusive and returns a word indicating the importance level ("very important" - from 7 to 10, "more important than usual"- from 4 to 6, "normal importance"- from 1 to 3). Use switch statement.
Expected Output:
Input: 5 Output: more important than usual
[File name and class name: L4Task3.java]
Task 4: Traffic Light Colors
Objective: Create a program that requests a color name (red, green, blue). If the color is red, output "Stop!". For green — "Go ahead." For blue — "Attention!". Use switch statement.
Expected Output:
Input: Green Output: Go ahead.
[File name and class name: L4Task4.java]
Task 5: Day of Week by Number
Objective: Request user to input a serial number of the day of the week (1, 2, 3, …, 7). Check the input and output the name of the day (Monday — 1, Tuesday — 2, etc.). Use switch statement.
Expected Output:
Please enter a number from 1 to 7: 2 The result: The 2-nd day of the week is Tuesday +++ Please enter a number from 1 to 7: 9 The result: There are no such days, please enter 1, 2, ..., 7
[File name and class name: L4Task5.java]