Enum in java.
enum in java
- It is a collection of named constant.
- It is declared with enum keywrod.
- Each enumeration constant is public, static and final by default.
- constant value can't be changed once it is defined.
- It is also called user defined data type.
- Value of enum should be in uppercase letters but not compulsory.
- new keyword is not used to create variable of enum.
- We can access the value of enum by using dot(.) operator.
- Syntax of enum
enum enum_name
{
value 1,value 2,value 3,.....,value n
}
- Example
enum Languange
{
C,
JAVA,
PHP,
ANDROID
}
class Program
{
public static void main(String[] args)
{
/*creating variable of enum*/
Languange myVar = Languange.ANDROID;
System.out.println(myVar);
}
}
/*
Output
ANDROID
*/
- Example:Enum within class
class Program
{
enum Languange
{
C,
JAVA,
PHP,
ANDROID
}
public static void main(String[] args)
{
/*creating variable of enum*/
Languange myVar = Languange.ANDROID;
System.out.println(myVar);
}
}
/*
Output
ANDROID
*/
- Example:Enum with switch
enum Languange
{
C,
JAVA,
PHP,
ANDROID
}
class Program
{
public static void main(String[] args)
{
/*creating variable of enum*/
Languange myVar = Languange.JAVA;
switch(myVar)
{
case C:
System.out.println("Fees:"+3500);
break;
case JAVA:
System.out.println("Fees:"+6000);
break;
case PHP:
System.out.println("Fees:"+8000);
break;
case ANDROID:
System.out.println("Fees:"+10000);
break;
}
}
}
/*
Output
Fees:6000
*/
- Example:Enum with constructor
- enum have also a constructor like class but enum constructor is called separately for each constant value of enum.
enum Languange
{
/*enum constants value*/
C,JAVA, PHP, ANDROID;
/*enum constructor*/
/*Note:enum constructor is
called separately for each constant
*/
private Languange()
{
System.out.println("called for: "+this.toString());
}
}
class Program
{
public static void main(String[] args)
{
/*creating variable of enum*/
Languange myVar = Languange.JAVA;
System.out.println(myVar);
}
}
/*
Output
called for: C
called for: JAVA
called for: PHP
called for: ANDROID
JAVA
*/
- Example:Enum with function
- we can also define function inside enum like a normal function and we can call it by using enum variable and dot(.) operator.
enum Languange
{
/*enum constants value*/
C,JAVA, PHP, ANDROID;
/*Defining function inside enum*/
public void fun()
{
System.out.println("called for: "+this.toString());
}
}
class Program
{
public static void main(String[] args)
{
/*creating variable of enum*/
Languange myVar = Languange.JAVA;
/*calling function*/
myVar.fun();
}
}
/*
Output
called for: JAVA
*/