Enum is similar to class so enum can be defined inside the class and outside the class. Following is an example to define the enum outside class.
EnumOutsideClass.java
[java]
enum Season { WINTER, SPRING, SUMMER, FALL }
public class EnumOutsideClass {
public static void main(String[] args) {
Season s=Season.SPRING;
System.out.println(s);
}
}
[/java]
Where the developer defined enum outside the class.
[java]enum Season { WINTER, SPRING, SUMMER, FALL } [/java]
Output
Now compile the code result will be as follows.
[java]
SPRING
[/java]
Following is an example to define the enum inside class.
EnumInsideClass.java
[java]
public class EnumInsideClass {
enum Season { WINTER, SPRING, SUMMER, FALL; };
public static void main(String[] args) {
Season s=Season.SPRING;//enum type is required to access WINTER
System.out.println(s);
}
}
[/java]
Here the developer defined enum inside the class as follows. Where the semicolon is an optional.
[java]enum Season { WINTER, SPRING, SUMMER, FALL; };[/java]
Output
Now compile the code result will be as follows.
[java]
SPRING
[/java]
Difference between enum and array
Array:
An array is a collection of homogeneous elements.
An array shares a same name with different index number, which starts from zero.
An array is reference type.
Enums:
An enums are collection of constants, which are recognized with string constants.
An enum variables are not initialized then the variables will be initialized automatically from 0 onwards
For more detailed overview on array
click here .