Enums and Enum Methods
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 50 of 87.
An enum (enumeration) is a special class type that represents a fixed set of constants. Instead of using arbitrary integers or strings to represent options like days of the week or order statuses, enums provide type-safe, readable values.
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.MONDAY;
System.out.println(today); // Prints: MONDAYEnums are more than simple constants—they're full classes. You can add fields, constructors, and methods to them:
enum Size {
SMALL(10), MEDIUM(20), LARGE(30);
private int price;
Size(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
}
System.out.println(Size.MEDIUM.getPrice()); // Prints: 20Every enum comes with useful built-in methods. The values() method returns an array of all constants, while valueOf() converts a string to the matching enum constant. The ordinal() method returns the position of the constant (starting from 0):
for (Day d : Day.values()) {
System.out.println(d + " is at position " + d.ordinal());
}
Day day = Day.valueOf("FRIDAY"); // Converts string to enumEnums are ideal when you have a known, fixed set of values that won't change at runtime, making your code safer and more expressive than using plain constants.
Challenge
EasyLet's build a coffee shop ordering system that showcases the power of enums with fields, constructors, and methods. You'll create a CoffeeSize enum that stores pricing information and a system to process customer orders.
You'll organize your code across three files:
CoffeeSize.java: Create an enum representing coffee sizes with associated prices. Your enum should have three constants:SMALL,MEDIUM, andLARGEwith prices of2.50,3.50, and4.50respectively.Each size needs a private
pricefield (double), a constructor to set it, and agetPrice()method to retrieve it. Also add agetDescription()method that returns a string in the format:[size name] - $[price](for example:SMALL - $2.5)Order.java: Create a class representing a coffee order. An Order has two private fields:customerName(String) andsize(CoffeeSize). Include a constructor to initialize both fields and getter methods for each.Add a
getReceipt()method that returns a multi-line string:Order for: [customerName] Size: [size description from getDescription()] Total: $[price from the size]Main.java: Bring your coffee shop to life! You'll receive two inputs: a customer name (String) and a size name (String like "SMALL", "MEDIUM", or "LARGE").First, use
CoffeeSize.valueOf()to convert the size string into the corresponding enum constant. Create an Order with the customer name and size, then print the receipt.After printing the receipt, print an empty line, then display the full menu by iterating through all
CoffeeSizevalues using thevalues()method. For each size, print its description on a separate line.
You will receive two inputs in order: customer name and size name (one of "SMALL", "MEDIUM", or "LARGE").
Notice how the enum encapsulates both the size identity and its associated price—much cleaner than using separate constants or magic numbers throughout your code!
Cheat sheet
An enum is a special class type representing a fixed set of constants, providing type-safe, readable values:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.MONDAY;
System.out.println(today); // Prints: MONDAYEnums can have fields, constructors, and methods:
enum Size {
SMALL(10), MEDIUM(20), LARGE(30);
private int price;
Size(int price) {
this.price = price;
}
public int getPrice() {
return price;
}
}
System.out.println(Size.MEDIUM.getPrice()); // Prints: 20Built-in enum methods:
values()- returns an array of all enum constantsvalueOf(String)- converts a string to the matching enum constantordinal()- returns the position of the constant (starting from 0)
for (Day d : Day.values()) {
System.out.println(d + " is at position " + d.ordinal());
}
Day day = Day.valueOf("FRIDAY"); // Converts string to enumTry it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String customerName = scanner.nextLine();
String sizeName = scanner.nextLine();
// TODO: Convert sizeName to CoffeeSize enum using valueOf()
// TODO: Create an Order with the customer name and size
// TODO: Print the receipt
// TODO: Print an empty line
// TODO: Display the full menu by iterating through all CoffeeSize values
// Hint: Use CoffeeSize.values() to get all enum constants
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System