Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson 4: Ternary Operator and Switch Statement

Lesson 4: Ternary Operator and Switch Statement

Completion requirements
Opened: Wednesday, 4 March 2026, 9:02 AM
Due: Wednesday, 18 March 2026, 9:46 AM

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 default block executes when none of the other blocks match.
  • ▶ The break keyword causes control to jump to the end of the switch after processing the block. If you omit break, 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:

  1. Within the folder 'java' create a new file named L4Lab1.java.
  2. In the very first line import the Scanner package:
    
    import ...;
  3. Add the class definition and main method:
    
    public class L4Lab1 {
        public static void main(...) {
    
        }
    }
  4. Place your cursor immediately after the open curly brace in the main method, then press enter to create a new line.
  5. Enter println() method to explain coffee sizes and request user selection:
    
    System.out.println("Coffee sizes: 1=small 2=medium 3=large");
  6. Request user to input with println() method:
    
    System.out.println("Please enter your selection:");
  7. Create Scanner object:
    
    Scanner scanner = ...;
  8. Assign the entered value to a string variable:
    
    String str = ...;
  9. Initialize a variable price with value 0:
    
    int price = 0;
  10. Create a switch-case statement to test the str variable:
    
    switch (str) {
        case "1":
            price += 25;
            break;
        case "2":
            price += 50;
            break;
        case "3":
            ...;
            ...;
    }
  11. 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;
    }
  12. Check the price variable and output the price if valid:
    
    if (price != 0) {
        System.out.printf("Please insert %d cents.%n", price);
    }
  13. Press F5 to run the program or use commands for terminal.
  14. Experiment with different values to see the output.
  15. 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:

  1. Create a new Java file named L4Lab2.java.
  2. Import the Scanner class at the top of the file.
  3. Define the class L4Lab2 with a main method.
  4. Inside the main method, create a Scanner object for user input.
  5. Prompt the user to enter a month number (1-12).
  6. Read the integer input from the user.
  7. 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"
  8. Add a default case to handle invalid month numbers (outside 1-12).
  9. Output the corresponding season name or error message.
  10. Close the Scanner object.
  11. 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:

  1. Create a new Java file named L4Lab3.java.
  2. Import the Scanner class.
  3. Define the class L4Lab3 with a main method.
  4. Create a Scanner object for user input.
  5. Prompt the user to enter a day of the week (e.g., Monday).
  6. Read the input string and convert it to lowercase using toLowerCase() for case-insensitive comparison.
  7. 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"
  8. Output the corresponding message.
  9. Close the Scanner object.
  10. 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]

© 2026 - some matherisals are taken from labs-org.ru

Mastering conditional operators and multi-way selection structures in Java.

◄ Lesson 3. Java Conditional statement IF
Lesson #5: Mathematical Functions in Java ►
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика