Menu
Topics Index
...
`

Using enum type as argument in switch - Java Example Program


Using enum type as argument in switch
enum Move
{
    LEFT,
    RIGHT,
    UP,
    DOWN;                
}

class EnumSwitchDemo
{
    public static void main(String arg[])
    {
        Move m1 = Move.DOWN;
        
        switch( m1 )   // LINE A
        {
            case LEFT: System.out.println( "You are going left" );
                                               break;
        
            case RIGHT: System.out.println( "You are going right" );
                                                break;
        
            case UP: System.out.println( "You are going up" );
                                             break;
        
            case DOWN: System.out.println( "You are going down" );
                                               break;
        
            default: System.out.println( "Invalid move" );
        }
              
    
    }
}
OUTPUT

You are going down

DESCRIPTION

Here, we are accessing the enum constant DOWN using the enum name Move. As we know, in enum, toString() is implicitly overridden to return its name. So, here m1 holds the enum constant DOWN. We are then passing it as an argument to switch (LINE A).

THINGS TO TRY
  • Try to access other enum constants as well in the same way and pass them as arguments to switch and observe the output.

© meritcampus 2019

All Rights Reserved.

Open In App