
- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use enum & switch statement in Java
Problem Description
How to use enum & switch statement?
Solution
This example displays how to check which enum member is selected using Switch statements.
enum Car { lamborghini,tata,audi,fiat,honda } public class Main { public static void main(String args[]){ Car c; c = Car.tata; switch(c) { case lamborghini: System.out.println("You choose lamborghini!"); break; case tata: System.out.println("You choose tata!"); break; case audi: System.out.println("You choose audi!"); break; case fiat: System.out.println("You choose fiat!"); break; case honda: System.out.println("You choose honda!"); break; default: System.out.println("I don't know your car."); break; } } }
Result
The above code sample will produce the following result.
You choose tata!
The following is an another example of enum & switch statement
public class MainClass { enum Choice { Choice1, Choice2, Choice3 } public static void main(String[] args) { Choice ch = Choice.Choice1; switch(ch) { case Choice1: System.out.println("Choice1 selected"); break; case Choice2: System.out.println("Choice2 selected"); break; case Choice3: System.out.println("Choice3 selected"); break; } } }
The above code sample will produce the following result.
Choice1 selected
java_methods.htm
Advertisements