Modern Java Types
Enums
Named Constants
Your app uses day-of-week values. Using integers (1=Monday, 2=Tuesday) is error-prone - what if someone passes 8? Enums define a fixed set of valid values. The compiler catches invalid values at compile time.
Define an enum
Create a type with fixed set of values.
DaysOfWeek.java
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
// Basic enum definition and usage
// Concept: enum - type-safe constants
enum DayOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class DaysOfWeek {
public static void main(String[] args) {
// Basic enum usage
DayOfWeek today = ;
System.out.println("Today is: " + today);
// Compare enums with ==
if (today == DayOfWeek.MONDAY) {
System.out.println("Start of work week");
}
// Get enum name as string
String dayName = today.name();
System.out.println("Day name: " + dayName);
// Get ordinal position (0-based index)
int position = today.ordinal();
System.out.println("Position in week: " + position);
// Try different day
DayOfWeek weekend = ;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
enum Name { VALUE1, VALUE2 } defines the allowed values.
enum
Type-safe named constants. Fixed set of values known at compile time.
Access enum values
Use enum values in your code.
AccessValues.java
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion
enum Priority {
LOW, MEDIUM, HIGH, URGENT
}
public class AccessValues {
public static void main(String[] args) {
// Get all enum values using values()
Priority[] allPriorities = Priority.values();
System.out.println("All priority levels:");
for (Priority p : allPriorities) {
System.out.println(" " + p);
}
// Count total values
System.out.println("\nTotal priorities: " + allPriorities.length);
// Convert string to enum using valueOf()
String input = ;
Priority taskPriority = Priority.valueOf(input);
System.out.println("\nTask priority: " + taskPriority);
// Check if specific value exists
Priority current = Priority.MEDIUM;
boolean isUrgent = (current == Priority.URGENT);
System.out.println("Is urgent? " + isUrgent);
// Print with ordinal
System.out.println("\nPriorities with ordinal:");
for (Priority p : Priority.values()) {
System.out.println(p.ordinal() + ": " + p);
}
}
}
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion
enum Priority {
LOW, MEDIUM, HIGH, URGENT
}
public class AccessValues {
public static void main(String[] args) {
// Get all enum values using values()
Priority[] allPriorities = Priority.values();
System.out.println("All priority levels:");
for (Priority p : allPriorities) {
System.out.println(" " + p);
}
// Count total values
System.out.println("\nTotal priorities: " + allPriorities.length);
// Convert string to enum using valueOf()
String input = ;
Priority taskPriority = Priority.valueOf(input);
System.out.println("\nTask priority: " + taskPriority);
// Check if specific value exists
Priority current = Priority.MEDIUM;
boolean isUrgent = (current == Priority.URGENT);
System.out.println("Is urgent? " + isUrgent);
// Print with ordinal
System.out.println("\nPriorities with ordinal:");
for (Priority p : Priority.values()) {
System.out.println(p.ordinal() + ": " + p);
}
}
}
// Accessing all enum values and converting from string
// Concept: values() - get all enum constants
// Concept: valueOf() - string to enum conversion
enum Priority {
LOW, MEDIUM, HIGH, URGENT
}
public class AccessValues {
public static void main(String[] args) {
// Get all enum values using values()
Priority[] allPriorities = Priority.values();
System.out.println("All priority levels:");
for (Priority p : allPriorities) {
System.out.println(" " + p);
}
// Count total values
System.out.println("\nTotal priorities: " + allPriorities.length);
// Convert string to enum using valueOf()
String input = ;
Priority taskPriority = Priority.valueOf(input);
System.out.println("\nTask priority: " + taskPriority);
// Check if specific value exists
Priority current = Priority.MEDIUM;
boolean isUrgent = (current == Priority.URGENT);
System.out.println("Is urgent? " + isUrgent);
// Print with ordinal
System.out.println("\nPriorities with ordinal:");
for (Priority p : Priority.values()) {
System.out.println(p.ordinal() + ": " + p);
}
}
}
EnumName.VALUE - access enum constant. Type-safe, IDE auto-completes.
Enum in switch
Match on enum values cleanly.
EnumInSwitch.java
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior
enum TrafficLight {
RED, YELLOW, GREEN
}
public class EnumInSwitch {
public static void main(String[] args) {
// Modern switch expression with enum
TrafficLight light = ;
String action = switch (light) {
case RED -> "Stop";
case YELLOW -> "Slow down";
case GREEN -> "Go";
};
System.out.println("Light: " + light);
System.out.println("Action: " + action);
// Classic switch statement
TrafficLight current = TrafficLight.YELLOW;
switch (current) {
case RED:
System.out.println("\n🔴 RED - Wait for green");
break;
case YELLOW:
System.out.println("\n🟡 YELLOW - Prepare to stop");
break;
case GREEN:
System.out.println("\n🟢 GREEN - Proceed");
break;
}
// Multiple cases same action
TrafficLight signal = TrafficLight.GREEN;
boolean shouldWait = switch (signal) {
case RED, YELLOW -> true;
case GREEN -> false;
};
System.out.println("\nShould wait? " + shouldWait);
}
}
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior
enum TrafficLight {
RED, YELLOW, GREEN
}
public class EnumInSwitch {
public static void main(String[] args) {
// Modern switch expression with enum
TrafficLight light = ;
String action = switch (light) {
case RED -> "Stop";
case YELLOW -> "Slow down";
case GREEN -> "Go";
};
System.out.println("Light: " + light);
System.out.println("Action: " + action);
// Classic switch statement
TrafficLight current = TrafficLight.YELLOW;
switch (current) {
case RED:
System.out.println("\n🔴 RED - Wait for green");
break;
case YELLOW:
System.out.println("\n🟡 YELLOW - Prepare to stop");
break;
case GREEN:
System.out.println("\n🟢 GREEN - Proceed");
break;
}
// Multiple cases same action
TrafficLight signal = TrafficLight.GREEN;
boolean shouldWait = switch (signal) {
case RED, YELLOW -> true;
case GREEN -> false;
};
System.out.println("\nShould wait? " + shouldWait);
}
}
// Using enums with switch expressions (Java 14+)
// Concept: switch with enum
// Concept: pattern - state-based behavior
enum TrafficLight {
RED, YELLOW, GREEN
}
public class EnumInSwitch {
public static void main(String[] args) {
// Modern switch expression with enum
TrafficLight light = ;
String action = switch (light) {
case RED -> "Stop";
case YELLOW -> "Slow down";
case GREEN -> "Go";
};
System.out.println("Light: " + light);
System.out.println("Action: " + action);
// Classic switch statement
TrafficLight current = TrafficLight.YELLOW;
switch (current) {
case RED:
System.out.println("\n🔴 RED - Wait for green");
break;
case YELLOW:
System.out.println("\n🟡 YELLOW - Prepare to stop");
break;
case GREEN:
System.out.println("\n🟢 GREEN - Proceed");
break;
}
// Multiple cases same action
TrafficLight signal = TrafficLight.GREEN;
boolean shouldWait = switch (signal) {
case RED, YELLOW -> true;
case GREEN -> false;
};
System.out.println("\nShould wait? " + shouldWait);
}
}
Switch on enum is exhaustive. Compiler warns if cases are missing.
Iterate all values
Loop through all enum constants.
IterateValues.java
// Iterating through enum values
// Concept: iteration - process all enum constants
// Concept: ordinal - enum position
enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
public class IterateValues {
public static void main(String[] args) {
// Iterate all months
System.out.println("All months:");
for (Month m : Month.values()) {
System.out.println(m);
}
// Print with month number (ordinal + 1)
System.out.println("\nMonths with numbers:");
for (Month m : Month.values()) {
int monthNumber = m.ordinal() + 1; // ordinal is 0-based
System.out.println(monthNumber + ". " + m);
}
// Find specific months
System.out.println("\nSummer months:");
for (Month m : Month.values()) {
if (m.ordinal() >= 5 && m.ordinal() <= 7) { // June-August
System.out.println(" " + m);
}
}
// Count months in first quarter
int q1Count = 0;
for (Month m : Month.values()) {
if (m.ordinal() < 3) { // Jan, Feb, Mar
q1Count++;
}
}
System.out.println("\nQ1 months: " + q1Count);
// Get specific month by ordinal
Month current = Month.values()[3]; // April (index 3)
System.out.println("Month at index 3: " + current);
}
}
EnumName.values() returns array of all constants.
values()
Built-in method returning all enum constants in declaration order.
Compare enums
Use == for enum comparison (not equals).
CompareEnums.java
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order
enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE
}
public class CompareEnums {
public static void main(String[] args) {
// Compare with == (recommended)
Size shirt = Size.MEDIUM;
Size pants = Size.MEDIUM;
if (shirt == pants) {
System.out.println("Same size");
}
// Can use equals() but == is better
boolean sameSize = shirt.equals(pants);
System.out.println("Using equals(): " + sameSize);
// Compare ordinal for ordering
Size small = Size.SMALL;
Size large = Size.LARGE;
if (small.ordinal() < large.ordinal()) {
System.out.println("\nSMALL comes before LARGE");
}
// Check if size is at least MEDIUM
Size customerSize = ;
boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
System.out.println("\nCustomer size: " + customerSize);
System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);
// Find max of two sizes
Size requested = Size.SMALL;
Size available = Size.MEDIUM;
Size actualSize = (requested.ordinal() > available.ordinal())
? requested : available;
System.out.println("\nRequested: " + requested);
System.out.println("Available: " + available);
System.out.println("Actual: " + actualSize);
}
}
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order
enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE
}
public class CompareEnums {
public static void main(String[] args) {
// Compare with == (recommended)
Size shirt = Size.MEDIUM;
Size pants = Size.MEDIUM;
if (shirt == pants) {
System.out.println("Same size");
}
// Can use equals() but == is better
boolean sameSize = shirt.equals(pants);
System.out.println("Using equals(): " + sameSize);
// Compare ordinal for ordering
Size small = Size.SMALL;
Size large = Size.LARGE;
if (small.ordinal() < large.ordinal()) {
System.out.println("\nSMALL comes before LARGE");
}
// Check if size is at least MEDIUM
Size customerSize = ;
boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
System.out.println("\nCustomer size: " + customerSize);
System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);
// Find max of two sizes
Size requested = Size.SMALL;
Size available = Size.MEDIUM;
Size actualSize = (requested.ordinal() > available.ordinal())
? requested : available;
System.out.println("\nRequested: " + requested);
System.out.println("Available: " + available);
System.out.println("Actual: " + actualSize);
}
}
// Comparing enum values
// Concept: comparison - enum equality and ordering
// Concept: natural order - based on declaration order
enum Size {
SMALL, MEDIUM, LARGE, EXTRA_LARGE
}
public class CompareEnums {
public static void main(String[] args) {
// Compare with == (recommended)
Size shirt = Size.MEDIUM;
Size pants = Size.MEDIUM;
if (shirt == pants) {
System.out.println("Same size");
}
// Can use equals() but == is better
boolean sameSize = shirt.equals(pants);
System.out.println("Using equals(): " + sameSize);
// Compare ordinal for ordering
Size small = Size.SMALL;
Size large = Size.LARGE;
if (small.ordinal() < large.ordinal()) {
System.out.println("\nSMALL comes before LARGE");
}
// Check if size is at least MEDIUM
Size customerSize = ;
boolean qualifiesForDiscount = customerSize.ordinal() >= Size.MEDIUM.ordinal();
System.out.println("\nCustomer size: " + customerSize);
System.out.println("Qualifies for bulk discount: " + qualifiesForDiscount);
// Find max of two sizes
Size requested = Size.SMALL;
Size available = Size.MEDIUM;
Size actualSize = (requested.ordinal() > available.ordinal())
? requested : available;
System.out.println("\nRequested: " + requested);
System.out.println("Available: " + available);
System.out.println("Actual: " + actualSize);
}
}
== is safe and preferred for enums. They're singletons.
Exercise: Practical.java
Build a state machine using enums