Java ProgramsControl FlowTraffic Signal Using Switch

Traffic Signal Using Switch in Java

beginner·  Control Flow  ·  Switch Statement

Problem

A switch statement maps each of the three fixed signal colors directly to the action a driver should take.

Given a traffic signal color, print the corresponding driving action.

Input
signal = "Yellow"
Output
Get ready

Java Program

Java
public class TrafficSignalSwitch { public static void main(String[] args) { String signal = "Yellow"; String action; switch (signal) { case "Red": action = "Stop"; break; case "Yellow": action = "Get ready"; break; case "Green": action = "Go"; break; default: action = "Invalid signal"; // required so action is always assigned } System.out.println(action); } }

Output

Get ready

Core Logic

Matching the signal color against each case picks out the matching driving action directly.

How It Works
  1. 1switch (signal) matches the color string against each case label.
  2. 2"Red" resolves to "Stop", "Yellow" to "Get ready", and "Green" to "Go".
  3. 3The default case handles any color outside those three, printing "Invalid signal".
For signal = "Yellow", the case "Yellow" branch matches directly and prints "Get ready".
💡

Key Point: Only three colors ever need a case here — a real traffic controller would also need to handle timing between them, which this simplified lookup doesn't model.

Key Concepts

switch statementString switchdefault case

Related Programs