Java Tutorial
IntroductionEnvironment SetupIDEBuild ManagementLanguage SpecificationBasic ProgramVariablesData TypesPackagesModifiersConditionalsLoopsObject OrientedClassesSuperInterfacesEnumStatic importInheritanceAbstractionEncapsulationPolymorphismBoxing & UnboxingConversion Formatting numbers Arrays Command line arguments in java Variable Number of arguments in Java Exception handling in Java String handling in Java StringBuffer and StringBuilder in Java Mathematical Operations in Java Date and Time in Java Regular expressions in Java Input output programming in Java File Handling Nested Classes Collections Generics Serialization Socket programming Multi-Threading Annotations Lambda Expressions Reflections in Java Singleton class in Java Runtime Class in JavaHow to load resource in JavaHow to load properties file in JavaAdvanced
Log4j – Logging framework in JavaInterview Questions in JavaIt is like a class where we define constants. We can declare constants using final keyword but it is not meaningful. So we use enums. Enums are also type-safe. Another advantage of using Enum is that we can declare methods as well as constructors in Enum. Below example demonstrates how we can use Enums in Java. We have created 2 Enums with names Coins and CoinsWithMethods. Since Enums are constant expressions, we can also use them in switch statement.
package enums;
/**
* Created by ssalunke on 13/04/2016.
*/
public class TestEnums {
public static void main(String [] args){
Coins c = Coins.FIVE;
//We can use enum in Switch statement as shown in below code
switch (c) {
case ONE:
System.out.println("You selected Coin type - ONE");
break;
case FIVE:
System.out.println("You selected Coin type - FIVE");
break;
case TEN:
System.out.println("You selected Coin type - TEN");
break;
}
CoinsWithMethods c1 = CoinsWithMethods.FIVE;
//below line accesses the method of enum
System.out.println("Year of Coin 5 is - > " + c1.getCoinYear());
}
}
enum Coins{
ONE,
FIVE,
TEN
}
enum CoinsWithMethods {
ONE(2002),
FIVE(2005),
TEN(2007);
private int coinYear;
private CoinsWithMethods(int a){
coinYear = a;
}
int getCoinYear(){
return this.coinYear;
}
}
Here is the output of above code.
You selected Coin type – FIVE
Year of Coin 5 is – > 2005
Web development and Automation testing
solutions delivered!!