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
Replay: real traced execution (multi-file project)
// 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 = DayOfWeek.MONDAY;
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 = DayOfWeek.SATURDAY;
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 = DayOfWeek.FRIDAY;
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 = DayOfWeek.SATURDAY;
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 = DayOfWeek.SUNDAY;
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 = DayOfWeek.SATURDAY;
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 = DayOfWeek.MONDAY;
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 = DayOfWeek.SUNDAY;
System.out.println("\nWeekend day: " + weekend);
System.out.println("Ordinal: " + weekend.ordinal());
}
}
today ← MONDAY
8public class DaysOfWeek {9 public static void main(String[] args) {10 // Basic enum usage11 DayOfWeek today→ MONDAY = DayOfWeek.MONDAY;12 //@today=DayOfWeek.MONDAY, DayOfWeek.FRIDAY, DayOfWeek.SUNDAY13 System.out.println("Today is: " + todayMONDAY);outputToday is: MONDAYif (today == DayOfWeek.MONDAY)
15// Compare enums with ==16if (todayMONDAY == DayOfWeek.MONDAY) {17 System.out.println("Start of work week");18}outputStart of work weekdayName ← MONDAY, position ← 0, weekend ← SATURDAY
20// Get enum name as string21String dayName→ MONDAY = today.name();22System.out.println("Day name: " + dayNameMONDAY);2324// Get ordinal position (0-based index)25int position→ 0 = today.ordinal();26System.out.println("Position in week: " + position0);2728//@help h129// Why use enum instead of String?30// 1. Type safety - compiler catches typos31// 2. Can't accidentally assign "Mondy" or "MONNDAY"32// 3. IDE autocomplete shows all valid options33//@end3435// Try different day36DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;37//@weekend=DayOfWeek.SATURDAY, DayOfWeek.SUNDAY38System.out.println("\nWeekend day: " + weekendSATURDAY);39System.out.println("Ordinal: " + weekend.ordinal());outputDay name: MONDAY Position in week: 0 Weekend day: SATURDAY Ordinal: 5
today ← FRIDAY, dayName ← FRIDAY, position ← 4, weekend ← SATURDAY
8public class DaysOfWeek {9 public static void main(String[] args) {10 // Basic enum usage11 DayOfWeek today→ FRIDAY = DayOfWeek.FRIDAY;12 System.out.println("Today is: " + todayFRIDAY);13 14 // Compare enums with ==15 if (today == DayOfWeek.MONDAY) {16 System.out.println("Start of work week");17 }18 19 // Get enum name as string20 String dayName→ FRIDAY = today.name();21 System.out.println("Day name: " + dayNameFRIDAY);22 23 // Get ordinal position (0-based index)24 int position→ 4 = today.ordinal();25 System.out.println("Position in week: " + position4);26 27 28 // Try different day29 DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;30 System.out.println("\nWeekend day: " + weekendSATURDAY);31 System.out.println("Ordinal: " + weekend.ordinal());outputToday is: FRIDAY Day name: FRIDAY Position in week: 4 Weekend day: SATURDAY Ordinal: 5
today ← SUNDAY, dayName ← SUNDAY, position ← 6, weekend ← SATURDAY
8public class DaysOfWeek {9 public static void main(String[] args) {10 // Basic enum usage11 DayOfWeek today→ SUNDAY = DayOfWeek.SUNDAY;12 System.out.println("Today is: " + todaySUNDAY);13 14 // Compare enums with ==15 if (today == DayOfWeek.MONDAY) {16 System.out.println("Start of work week");17 }18 19 // Get enum name as string20 String dayName→ SUNDAY = today.name();21 System.out.println("Day name: " + dayNameSUNDAY);22 23 // Get ordinal position (0-based index)24 int position→ 6 = today.ordinal();25 System.out.println("Position in week: " + position6);26 27 28 // Try different day29 DayOfWeek weekend→ SATURDAY = DayOfWeek.SATURDAY;30 System.out.println("\nWeekend day: " + weekendSATURDAY);31 System.out.println("Ordinal: " + weekend.ordinal());outputToday is: SUNDAY Day name: SUNDAY Position in week: 6 Weekend day: SATURDAY Ordinal: 5
today ← MONDAY
8public class DaysOfWeek {9 public static void main(String[] args) {10 // Basic enum usage11 DayOfWeek today→ MONDAY = DayOfWeek.MONDAY;12 System.out.println("Today is: " + todayMONDAY);outputToday is: MONDAYif (today == DayOfWeek.MONDAY)
14// Compare enums with ==15if (todayMONDAY == DayOfWeek.MONDAY) {16 System.out.println("Start of work week");17}outputStart of work weekdayName ← MONDAY, position ← 0, weekend ← SUNDAY
19// Get enum name as string20String dayName→ MONDAY = today.name();21System.out.println("Day name: " + dayNameMONDAY);2223// Get ordinal position (0-based index)24int position→ 0 = today.ordinal();25System.out.println("Position in week: " + position0);262728// Try different day29DayOfWeek weekend→ SUNDAY = DayOfWeek.SUNDAY;30System.out.println("\nWeekend day: " + weekendSUNDAY);31System.out.println("Ordinal: " + weekend.ordinal());outputDay name: MONDAY Position in week: 0 Weekend day: SUNDAY Ordinal: 6
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
Replay: real traced execution (multi-file project)
// 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 = "HIGH";
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 = "LOW";
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 = "URGENT";
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);
}
}
}
public static void main(String[] args)
9public class AccessValues {10 public static void main(String[] args) {11 // Get all enum values using values()12 Priority[] allPriorities = Priority.values();13 14 System.out.println("All priority levels:");15 for (Priority p : allPriorities) {outputAll priority levels:for (Priority p : allPriorities)
pass 1 of 414System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16 System.out.println(" " + pLOW);17}output LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT input ← HIGH, taskPriority ← HIGH, current ← MEDIUM, isUrgent ← false
19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ HIGH = "HIGH";24//@input="HIGH", "LOW", "URGENT"25Priority taskPriority→ HIGH = Priority.valueOf(inputHIGH);26System.out.println("\nTask priority: " + taskPriorityHIGH);2728//@help h129// valueOf() throws IllegalArgumentException if string doesn't match30// Always match exact case: "HIGH" works, "high" or "High" don't31//@end3233// Check if specific value exists34Priority current→ MEDIUM = Priority.MEDIUM;35boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);36System.out.println("Is urgent? " + isUrgentfalse);3738// Print with ordinal39System.out.println("\nPriorities with ordinal:");40for (Priority p : Priority.values()) {output Total priorities: 4 Task priority: HIGH Is urgent? false Priorities with ordinal:for (Priority p : Priority.values())
pass 1 of 439System.out.println("\nPriorities with ordinal:");40for (Priority pLOW : Priority.values()) {41 System.out.println(p.ordinal() + ": " + pLOW);42}output0: LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT
public static void main(String[] args)
9public class AccessValues {10 public static void main(String[] args) {11 // Get all enum values using values()12 Priority[] allPriorities = Priority.values();13 14 System.out.println("All priority levels:");15 for (Priority p : allPriorities) {outputAll priority levels:for (Priority p : allPriorities)
pass 1 of 414System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16 System.out.println(" " + pLOW);17}output LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT input ← LOW, taskPriority ← LOW, current ← MEDIUM, isUrgent ← false
19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ LOW = "LOW";24Priority taskPriority→ LOW = Priority.valueOf(inputLOW);25System.out.println("\nTask priority: " + taskPriorityLOW);262728// Check if specific value exists29Priority current→ MEDIUM = Priority.MEDIUM;30boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);31System.out.println("Is urgent? " + isUrgentfalse);3233// Print with ordinal34System.out.println("\nPriorities with ordinal:");35for (Priority p : Priority.values()) {output Total priorities: 4 Task priority: LOW Is urgent? false Priorities with ordinal:for (Priority p : Priority.values())
pass 1 of 434System.out.println("\nPriorities with ordinal:");35for (Priority pLOW : Priority.values()) {36 System.out.println(p.ordinal() + ": " + pLOW);37}output0: LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT
public static void main(String[] args)
9public class AccessValues {10 public static void main(String[] args) {11 // Get all enum values using values()12 Priority[] allPriorities = Priority.values();13 14 System.out.println("All priority levels:");15 for (Priority p : allPriorities) {outputAll priority levels:for (Priority p : allPriorities)
pass 1 of 414System.out.println("All priority levels:");15for (Priority pLOW : allPriorities) {16 System.out.println(" " + pLOW);17}output LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT input ← URGENT, taskPriority ← URGENT, current ← MEDIUM, isUrgent ← false
19// Count total values20System.out.println("\nTotal priorities: " + allPriorities.length4);2122// Convert string to enum using valueOf()23String input→ URGENT = "URGENT";24Priority taskPriority→ URGENT = Priority.valueOf(inputURGENT);25System.out.println("\nTask priority: " + taskPriorityURGENT);262728// Check if specific value exists29Priority current→ MEDIUM = Priority.MEDIUM;30boolean isUrgent→ false = (currentMEDIUM == Priority.URGENT);31System.out.println("Is urgent? " + isUrgentfalse);3233// Print with ordinal34System.out.println("\nPriorities with ordinal:");35for (Priority p : Priority.values()) {output Total priorities: 4 Task priority: URGENT Is urgent? false Priorities with ordinal:for (Priority p : Priority.values())
pass 1 of 434System.out.println("\nPriorities with ordinal:");35for (Priority pLOW : Priority.values()) {36 System.out.println(p.ordinal() + ": " + pLOW);37}output0: LOWAll 4 passes — pass 1 is the card above pass p1 LOW 2 MEDIUM 3 HIGH 4 URGENT
EnumName.VALUE - access enum constant. Type-safe, IDE auto-completes.
Enum in switch
Match on enum values cleanly.
EnumInSwitch.java
Replay: real traced execution (multi-file project)
// 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 = TrafficLight.RED;
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 = TrafficLight.YELLOW;
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 = TrafficLight.GREEN;
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);
}
}
light ← RED, action ← Stop, current ← YELLOW
9public class EnumInSwitch {10 public static void main(String[] args) {11 // Modern switch expression with enum12 TrafficLight light→ RED = TrafficLight.RED;13 //@light=TrafficLight.RED, TrafficLight.YELLOW, TrafficLight.GREEN14 15 String action→ Stop = switch (light) {16 case RED -> "Stop";17 case YELLOW -> "Slow down";18 case GREEN -> "Go";19 };20 21 System.out.println("Light: " + lightRED);22 System.out.println("Action: " + actionStop);23 24 // Classic switch statement25 TrafficLight current→ YELLOW = TrafficLight.YELLOW;outputLight: RED Action: Stopswitch (current)
27switch (currentYELLOW) {28 case RED:29 System.out.println("\n🔴 RED - Wait for green");case YELLOW:
30 break;31case YELLOW:32 System.out.println("\n🟡 YELLOW - Prepare to stop");33 break;34case GREEN:output 🟡 YELLOW - Prepare to stopsignal ← GREEN, shouldWait ← false
45// Multiple cases same action46TrafficLight signal→ GREEN = TrafficLight.GREEN;4748boolean shouldWait→ false = switch (signal) {49 case RED, YELLOW -> true;50 case GREEN -> false;51};5253System.out.println("\nShould wait? " + shouldWaitfalse);output Should wait? false
light ← YELLOW, action ← Slow down, current ← YELLOW
9public class EnumInSwitch {10 public static void main(String[] args) {11 // Modern switch expression with enum12 TrafficLight light→ YELLOW = TrafficLight.YELLOW;13 14 String action→ Slow down = switch (light) {15 case RED -> "Stop";16 case YELLOW -> "Slow down";17 case GREEN -> "Go";18 };19 20 System.out.println("Light: " + lightYELLOW);21 System.out.println("Action: " + actionSlow down);22 23 // Classic switch statement24 TrafficLight current→ YELLOW = TrafficLight.YELLOW;outputLight: YELLOW Action: Slow downswitch (current)
26switch (currentYELLOW) {27 case RED:28 System.out.println("\n🔴 RED - Wait for green");case YELLOW:
29 break;30case YELLOW:31 System.out.println("\n🟡 YELLOW - Prepare to stop");32 break;33case GREEN:output 🟡 YELLOW - Prepare to stopsignal ← GREEN, shouldWait ← false
39// Multiple cases same action40TrafficLight signal→ GREEN = TrafficLight.GREEN;4142boolean shouldWait→ false = switch (signal) {43 case RED, YELLOW -> true;44 case GREEN -> false;45};4647System.out.println("\nShould wait? " + shouldWaitfalse);output Should wait? false
light ← GREEN, action ← Go, current ← YELLOW
9public class EnumInSwitch {10 public static void main(String[] args) {11 // Modern switch expression with enum12 TrafficLight light→ GREEN = TrafficLight.GREEN;13 14 String action→ Go = switch (light) {15 case RED -> "Stop";16 case YELLOW -> "Slow down";17 case GREEN -> "Go";18 };19 20 System.out.println("Light: " + lightGREEN);21 System.out.println("Action: " + actionGo);22 23 // Classic switch statement24 TrafficLight current→ YELLOW = TrafficLight.YELLOW;outputLight: GREEN Action: Goswitch (current)
26switch (currentYELLOW) {27 case RED:28 System.out.println("\n🔴 RED - Wait for green");case YELLOW:
29 break;30case YELLOW:31 System.out.println("\n🟡 YELLOW - Prepare to stop");32 break;33case GREEN:output 🟡 YELLOW - Prepare to stopsignal ← GREEN, shouldWait ← false
39// Multiple cases same action40TrafficLight signal→ GREEN = TrafficLight.GREEN;4142boolean shouldWait→ false = switch (signal) {43 case RED, YELLOW -> true;44 case GREEN -> false;45};4647System.out.println("\nShould wait? " + shouldWaitfalse);output Should wait? false
Switch on enum is exhaustive. Compiler warns if cases are missing.
Iterate all values
Loop through all enum constants.
IterateValues.java
Replay: real traced execution (multi-file project)
// 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);
}
}
public static void main(String[] args)
10public class IterateValues {11 public static void main(String[] args) {12 // Iterate all months13 System.out.println("All months:");14 for (Month m : Month.values()) {outputAll months:for (Month m : Month.values())
pass 1 of 1213System.out.println("All months:");14for (Month mJANUARY : Month.values()) {15 System.out.println(mJANUARY);16}outputJANUARYAll 12 passes — pass 1 is the card above pass m1 JANUARY 2 FEBRUARY 3 MARCH 4 APRIL 5 MAY 6 JUNE 7 JULY 8 AUGUST 9 SEPTEMBER 10 OCTOBER 11 NOVEMBER 12 DECEMBER System.out.println(" Months with numbers:");
18// Print with month number (ordinal + 1)19System.out.println("\nMonths with numbers:");20for (Month m : Month.values()) {output Months with numbers:monthNumber ← 1
pass 1 of 1219System.out.println("\nMonths with numbers:");20for (Month mJANUARY : Month.values()) {21 int monthNumber→ 1 = m.ordinal() + 1; // ordinal is 0-based22 System.out.println(monthNumber1 + ". " + mJANUARY);23}output1. JANUARYAll 12 passes — pass 1 is the card above pass mmonthNumber1 JANUARY 1 2 FEBRUARY 2 3 MARCH 3 4 APRIL 4 5 MAY 5 6 JUNE 6 7 JULY 7 8 AUGUST 8 9 SEPTEMBER 9 10 OCTOBER 10 11 NOVEMBER 11 12 DECEMBER 12 System.out.println(" Summer months:");
30// Find specific months31System.out.println("\nSummer months:");32for (Month m : Month.values()) {output Summer months:for (Month m : Month.values())
pass 1 of 1231System.out.println("\nSummer months:");32for (Month mJANUARY : Month.values()) {33 if (m.ordinal() >= 5 && m.ordinal() <= 7) { // June-AugustAll 12 passes — pass 1 is the card above pass m1 JANUARY 2 FEBRUARY 3 MARCH 4 APRIL 5 MAY 6 JUNE 7 JULY 8 AUGUST 9 SEPTEMBER 10 OCTOBER 11 NOVEMBER 12 DECEMBER if (m.ordinal() >= 5 && m.ordinal() <= 7)
pass 1 of 332for (Month m : Month.values()) {33 if (m.ordinal() >= 5 && m.ordinal() <= 7) { // June-August34 System.out.println(" " + mJUNE);35 }output JUNEAll 3 passes — pass 1 is the card above pass m1 JUNE 2 JULY 3 AUGUST q1Count ← 0
38// Count months in first quarter39int q1Count→ 0 = 0;40for (Month m : Month.values()) {for (Month m : Month.values())
pass 1 of 1239int q1Count = 0;40for (Month mJANUARY : Month.values()) {41 if (m.ordinal() < 3) { // Jan, Feb, MarAll 12 passes — pass 1 is the card above pass m1 JANUARY 2 FEBRUARY 3 MARCH 4 APRIL 5 MAY 6 JUNE 7 JULY 8 AUGUST 9 SEPTEMBER 10 OCTOBER 11 NOVEMBER 12 DECEMBER q1Count ← 1
pass 1 of 340for (Month m : Month.values()) {41 if (m.ordinal() < 3) { // Jan, Feb, Mar42 q1Count→ 1++;43 }All 3 passes — pass 1 is the card above pass q1Count1 0 → 1 2 1 → 2 3 2 → 3 current ← APRIL
44 }45 System.out.println("\nQ1 months: " + q1Count3);46 47 // Get specific month by ordinal48 Month current→ APRIL = Month.values()[3]; // April (index 3)49 System.out.println("Month at index 3: " + currentAPRIL);50}output Q1 months: 3 Month at index 3: APRIL
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
Replay: real traced execution (multi-file project)
// 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 = Size.LARGE;
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 = Size.SMALL;
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 = Size.EXTRA_LARGE;
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);
}
}
shirt ← MEDIUM, pants ← MEDIUM
9public class CompareEnums {10 public static void main(String[] args) {11 // Compare with == (recommended)12 Size shirt→ MEDIUM = Size.MEDIUM;13 Size pants→ MEDIUM = Size.MEDIUM;if (shirt == pants)
15if (shirtMEDIUM == pantsMEDIUM) {16 System.out.println("Same size");17}outputSame sizesameSize ← true, small ← SMALL, large ← LARGE
19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);2223//@help h124// Use == for enum comparison (simpler, safer)25// equals() works but == is idiomatic for enums26// Enums are singleton per constant27//@end2829// Compare ordinal for ordering30Size small→ SMALL = Size.SMALL;31Size large→ LARGE = Size.LARGE;outputUsing equals(): trueif (small.ordinal() < large.ordinal())
33if (small.ordinal() < large.ordinal()) {34 System.out.println("\nSMALL comes before LARGE");35}output SMALL comes before LARGEcustomerSize ← LARGE, qualifiesForDiscount ← true, requested ← SMALL
37// Check if size is at least MEDIUM38Size customerSize→ LARGE = Size.LARGE;39//@customerSize=Size.LARGE, Size.SMALL, Size.EXTRA_LARGE40boolean qualifiesForDiscount→ true = customerSize.ordinal() >= Size.MEDIUM.ordinal();41System.out.println("\nCustomer size: " + customerSizeLARGE);42System.out.println("Qualifies for bulk discount: " + qualifiesForDiscounttrue);4344// Find max of two sizes45Size requested→ SMALL = Size.SMALL;46Size available→ MEDIUM = Size.MEDIUM;4748Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 49 ? requestedSMALL : availableMEDIUM;50System.out.println("\nRequested: " + requestedSMALL);51System.out.println("Available: " + availableMEDIUM);52System.out.println("Actual: " + actualSizeMEDIUM);output Customer size: LARGE Qualifies for bulk discount: true Requested: SMALL Available: MEDIUM Actual: MEDIUM
shirt ← MEDIUM, pants ← MEDIUM
9public class CompareEnums {10 public static void main(String[] args) {11 // Compare with == (recommended)12 Size shirt→ MEDIUM = Size.MEDIUM;13 Size pants→ MEDIUM = Size.MEDIUM;if (shirt == pants)
15if (shirtMEDIUM == pantsMEDIUM) {16 System.out.println("Same size");17}outputSame sizesameSize ← true, small ← SMALL, large ← LARGE
19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);222324// Compare ordinal for ordering25Size small→ SMALL = Size.SMALL;26Size large→ LARGE = Size.LARGE;outputUsing equals(): trueif (small.ordinal() < large.ordinal())
28if (small.ordinal() < large.ordinal()) {29 System.out.println("\nSMALL comes before LARGE");30}output SMALL comes before LARGEcustomerSize ← SMALL, qualifiesForDiscount ← false, requested ← SMALL
32// Check if size is at least MEDIUM33Size customerSize→ SMALL = Size.SMALL;34boolean qualifiesForDiscount→ false = customerSize.ordinal() >= Size.MEDIUM.ordinal();35System.out.println("\nCustomer size: " + customerSizeSMALL);36System.out.println("Qualifies for bulk discount: " + qualifiesForDiscountfalse);3738// Find max of two sizes39Size requested→ SMALL = Size.SMALL;40Size available→ MEDIUM = Size.MEDIUM;4142Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 43 ? requestedSMALL : availableMEDIUM;44System.out.println("\nRequested: " + requestedSMALL);45System.out.println("Available: " + availableMEDIUM);46System.out.println("Actual: " + actualSizeMEDIUM);output Customer size: SMALL Qualifies for bulk discount: false Requested: SMALL Available: MEDIUM Actual: MEDIUM
shirt ← MEDIUM, pants ← MEDIUM
9public class CompareEnums {10 public static void main(String[] args) {11 // Compare with == (recommended)12 Size shirt→ MEDIUM = Size.MEDIUM;13 Size pants→ MEDIUM = Size.MEDIUM;if (shirt == pants)
15if (shirtMEDIUM == pantsMEDIUM) {16 System.out.println("Same size");17}outputSame sizesameSize ← true, small ← SMALL, large ← LARGE
19// Can use equals() but == is better20boolean sameSize→ true = shirt.equals(pantsMEDIUM);21System.out.println("Using equals(): " + sameSizetrue);222324// Compare ordinal for ordering25Size small→ SMALL = Size.SMALL;26Size large→ LARGE = Size.LARGE;outputUsing equals(): trueif (small.ordinal() < large.ordinal())
28if (small.ordinal() < large.ordinal()) {29 System.out.println("\nSMALL comes before LARGE");30}output SMALL comes before LARGEcustomerSize ← EXTRA_LARGE, qualifiesForDiscount ← true, requested ← SMALL
32// Check if size is at least MEDIUM33Size customerSize→ EXTRA_LARGE = Size.EXTRA_LARGE;34boolean qualifiesForDiscount→ true = customerSize.ordinal() >= Size.MEDIUM.ordinal();35System.out.println("\nCustomer size: " + customerSizeEXTRA_LARGE);36System.out.println("Qualifies for bulk discount: " + qualifiesForDiscounttrue);3738// Find max of two sizes39Size requested→ SMALL = Size.SMALL;40Size available→ MEDIUM = Size.MEDIUM;4142Size actualSize→ MEDIUM = (requested.ordinal() > available.ordinal()) 43 ? requestedSMALL : availableMEDIUM;44System.out.println("\nRequested: " + requestedSMALL);45System.out.println("Available: " + availableMEDIUM);46System.out.println("Actual: " + actualSizeMEDIUM);output Customer size: EXTRA_LARGE Qualifies for bulk discount: true Requested: SMALL Available: MEDIUM Actual: MEDIUM
== is safe and preferred for enums. They're singletons.
Exercise: Practical.java
Build a state machine using enums