Enums in Java
Syntax of declaring enum in a program is as shown:
Another example is a list of directions we use namely North, West, South, East. It can be expressed as shown in this code:
Enum Direction{ NORTH, SOUTH, EAST, WEST; // Mention the constants }
The semicolon at the end is not mandatory and is the choice of the coder. According to JAVA conventions constants in enum should be declared in capital letters. It is important to note that we cannot create an object of enum. Enum can be defined as a part of class or outside the class.
Enum used inside a class: -
package com.java1; public class TestEnum { enum FlightBrand{ Emirates,BritishAirways,AirAsia; } public static void main(String[] args) { FlightBrand k = FlightBrand.Emirates; System.out.println("The selected Flight Brand is " +k); } }
Enum used outside a class: -
package com.java1; public class TestEnum { public static void main(String[] args) { FlightBrand k = FlightBrand.Emirates; System.out.println("The selected Flight Brand is " +k); } } enum FlightBrand{ Emirates,BritishAirways,AirAsia; }In both cases the output is
The selected Flight Brand is Emirates
Methods and variables can also be declared inside enum. This property of enum is only available in Java but not in C/C++. This is portrayed in the following example:
package com.java1; public class TestEnum1 { enum AndroidVersion{ Lolipop(5.0),Oreo(8.0),KitKat(4.4),Marshmallow(6.0); double version; AndroidVersion(double v) { version = v; } public double getVersion() { return version; } } public static void main(String[] args) { System.out.println(AndroidVersion.Lolipop.getVersion()); } }
First line in the code should be list of constants followed by methods, variables and constructor. Enum can be passed as an argument in switch case:
package com.java1; public class SwitchEnum { enum Color { RED,GREEN,BLUE } public static void main(String[] args) { Color k; k = Color.GREEN; switch(k) { case RED: System.out.println("I am "+k); break; case GREEN: System.out.println("I am "+k); break; case BLUE: System.out.println("I am "+k); break; } } }Output:
I am GREEN
See Also
Overriding equals() in Java Image Comparison in Java Java - PermGen space vs Heap space Java - PermGen space vs MetaSpace Implement Counting Sort using Java + Performance Analysis Java 8 Features Java Miscelleneous Topics Java Basic Topics Java- Main Menu