Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

Java Enums with Fields, Methods and switch

An OrderStatus can only be PLACED, PACKED, SHIPPED or DELIVERED, and the compiler rejects the typo "SHIPED". CoffeeSize constants carry their own ml and price, values() lists them, valueOf finds one, and a switch picks a cup for each.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

What you will learn

  • Declare an enum as a fixed list of constants and compare them with ==
  • Give enum constants their own data with fields and a constructor
  • Use values() and valueOf() and add methods to an enum
  • Switch on an enum without a default when every constant is covered

Before you start

  • Java if, else and switch
  • Java constructors and the this keyword

Sometimes a variable should only ever hold one value from a fixed list. An order can be placed, packed, shipped or delivered, and nothing else. An enum gives you exactly that: a type with a fixed list of values.

A fixed list of allowed values

package org.studyeasy.s03l17;

// Every status an order can have: nothing else is allowed
public enum OrderStatus {
    PLACED, PACKED, SHIPPED, DELIVERED
}

It says enum, not class. The constants are written in capitals with commas between them. An OrderStatus variable can only be one of these four; OrderStatus.CANCELLED is "cannot find symbol".

package org.studyeasy.s03l17;

public class Ex01_EnumBasics {
    public static void main(String[] args) {
        OrderStatus status = OrderStatus.PACKED;
        System.out.println("Now: " + status);

        status = OrderStatus.SHIPPED;
        System.out.println("Now: " + status);

        if (status == OrderStatus.SHIPPED) {
            System.out.println("Your order is on its way");
        }
    }
}
Now: PACKED
Now: SHIPPED
Your order is on its way

Printing a constant shows its name. You compare constants with ==: each one exists exactly once. Try status = "SHIPED"; (text, and misspelt) and the compiler says incompatible types: String cannot be converted to OrderStatus. Text isn't an OrderStatus, and the compiler checks the list for you before the program runs.

Constants that carry data

package org.studyeasy.s03l17;

// Each size carries its own millilitres and price
public enum CoffeeSize {
    SMALL(250, 120),
    MEDIUM(350, 150),
    LARGE(450, 180);

    private final int ml;
    private final int price;

    CoffeeSize(int ml, int price) {
        this.ml = ml;
        this.price = price;
    }

    public int getMl() {
        return ml;
    }

    public int priceFor(int cups) {
        return price * cups;
    }
}

Now each constant passes two numbers in brackets: SMALL is 250 ml for 120 rupees. The fields ml and price are private final, so every constant keeps its own copy. You can think of the enum as a tiny class with a fixed menu.

When CoffeeSize loads, Java builds each constant once by running the constructor: SMALL with ml 250 and price 120, MEDIUM with 350 and 150, LARGE with 450 and 180. There is no new; these three are all there is. CoffeeSize loads: the constructor runs once per constant SMALLml 250price 120 MEDIUMml 350price 150 LARGEml 450price 180 No new: these three objects are all there is.
Each constant is built once, with its own values.

Java runs the constructor once for each constant when the enum loads. You never write new: new CoffeeSize(500, 200) fails with "enum classes may not be instantiated".

Loop them, look one up

package org.studyeasy.s03l17;

public class Ex02_EnumFields {
    public static void main(String[] args) {
        // values(): every size, in the order they are written
        for (CoffeeSize size : CoffeeSize.values()) {
            System.out.println(size + " = " + size.getMl() + " ml");
        }

        // valueOf(): text in, constant out
        CoffeeSize pick = CoffeeSize.valueOf("LARGE");
        int bill = pick.priceFor(2);
        System.out.println("2 x " + pick + " = Rs " + bill);
    }
}
SMALL = 250 ml
MEDIUM = 350 ml
LARGE = 450 ml
2 x LARGE = Rs 360

values() gives every constant in the order they're written. valueOf("LARGE") turns text into the constant; the text must match the name exactly. valueOf("large") compiles but throws IllegalArgumentException at run time. Methods work like in any class: LARGE's price is 180, so priceFor(2) is 360.

One cup per size: switch on an enum

package org.studyeasy.s03l17;

public class Ex03_EnumSwitch {
    public static void main(String[] args) {
        for (CoffeeSize size : CoffeeSize.values()) {
            // Each size goes in its own cup
            String cup = switch (size) {
                case SMALL -> "Paper cup";
                case MEDIUM -> "Regular mug";
                case LARGE -> "Travel mug";
            };
            int price = size.priceFor(1);
            System.out.println(size + ": " + cup + ", Rs " + price);
        }
    }
}
SMALL: Paper cup, Rs 120
MEDIUM: Regular mug, Rs 150
LARGE: Travel mug, Rs 180

Inside the switch you write just the constant's name, SMALL, not CoffeeSize.SMALL. There's one case per constant, and because all three are covered, this switch expression needs no default. Delete the case LARGE line and the compiler says the switch expression does not cover all possible input values. That's a safety net: add a new size to the enum and every switch that forgot it stops compiling.

Recap

IdeaExample
Fixed list of constantsPLACED, PACKED, SHIPPED, DELIVERED
Comparestatus == OrderStatus.SHIPPED
Constants with dataSMALL(250, 120)
Constructorruns once per constant; no new
List and look upvalues(), valueOf("LARGE")
switchone case per constant; no default when all are covered

Keep going in Java · 39 of 79

Previous
Java Nested, Inner and Anonymous Classes
Next post
Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Classes and Objects: One Blueprint, Many Cars

Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.

Java Constructors and the this Keyword

A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.

Java Instance Methods, Getters, Setters and toString

Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.

Java static: Fields, Methods and Blocks Shared by the Whole Class

A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.

On this page

  • A fixed list of allowed values
  • Constants that carry data
  • Loop them, look one up
  • One cup per size: switch on an enum
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.