dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Using Enum Effectively

Learn how to use enum effectively in a switch case block.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Learn how to use enum effectively in a switch case block. There are multiple advantages to avoiding mistakes, especially since the originals are defined in the enum.

public class EnumColors 
{
public static void main(String args[])
{
Color color = Color.WHITE;
String colorArg = (args.length == 0) ? "White" : args[0];
if (args.length == 0)
System.out.println("No Color provided. Hence assigning WHITE");

if (colorArg != "")
{

if (colorArg.equalsIgnoreCase("Saffron"))
color = Color.SAFFRON;
else if (colorArg.equalsIgnoreCase("White"))
color = Color.WHITE;
else if (colorArg.equalsIgnoreCase("Green"))
color = Color.GREEN;
}

switch(color) 
{
case SAFFRON:
System.out.println("Saffron Color");
break;
case WHITE:
System.out.println("White Color");
break;
case GREEN:
System.out.println("Green Color");
break;
}
}
}
enum Color {
SAFFRON,
WHITE,
GREEN
}

Expected output:

[root@mypc]# java EnumColors
No Color provided. Hence assigning WHITE
White Color
[root@mypc]# java EnumColors white
White Color
[root@mypc]# java EnumColors green
Green Color

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date