Topics Index

Using enum type as argument in switch - Java Example Program

Using enum type as argument in switch
enum Move

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" );
            case RIGHT: System.out.println( "You are going right" );
            case UP: System.out.println( "You are going up" );
            case DOWN: System.out.println( "You are going down" );
            default: System.out.println( "Invalid move" );

You are going down


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).

  • 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