Enum in Java

  • Enum are introduce in Java 5.0
  • Enums can help reduce the bugs in your code.
  • Enum improves compile-time type safety
  • Enum can be declared outside or inside a class, but NOT in a method.
  • Enum declared outside a class must NOT be marked static, final, abstract, protected, or private.
  • Enums file can contain constructors, methods, variables, and constant in bodies.
  • Enum in java is a data type that contains fixed set of constants.
  • Enum constructors can have arguments, and can be overloaded.
  • Enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
  • Enums extend the java.lang.Enum class implicitly
  • int enums are compile-time constants, they are compiled into the clients that use them.
  • Enum Example , Enum Iteration, Enum Fields, Enum Methods, Enums in switch Statements

    		public enum Level {
    
    			HIGH(3), // calls constructor with code 3
    			MEDIUM(2), // calls constructor with code 2
    			LOW(1) // calls constructor with code 1
    			; // semicolon needed when fields / methods follow
    
    			// Enum Fields
    			private final int levelCode;
    
    			private Level(int levelCode) {
    				this.levelCode = levelCode;
    			}
    
    			// Enum Methods
    			public int getLevelCode() {
    				return this.levelCode;
    			}
    			
    			public static void main(String args[]) {
    				Level level = Level.HIGH;
    				System.out.println("Level code ="+level.getLevelCode());
    				
    				// Enum Iteration
    				for (Level tempLevel : Level.values()) {
    					System.out.println("Iteration Level = "+tempLevel);
    				}
    				
    				// Enums in switch Statements
    				Level l = Level.LOW;  //assign some Level constant to it
    				switch (l) {
    					case HIGH   : System.out.println("switch to HIGH LEVEL"); break;
    					case MEDIUM : System.out.println("switch to MEDIUM LEVEL"); break;
    					case LOW    : System.out.println("switch to LOW LEVEL"); break;
    				}
    			}
    		}