Popular Searches
Popular Course Categories
Popular Courses

Applying Wrapper Classes and Enums in Practical Programs

Applying Wrapper Classes and Enums in Practical Programs

Wrapper Classes, Autoboxing, and Enumerations

Applying Wrapper Classes and Enums in Practical Programs

Course: Core Java Training

Topic: Applying Wrapper Classes and Enums in Practical Programs

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction

Java provides several built-in features that make programs more flexible, readable, and reliable. Two important features are wrapper classes and enumerations (enums). Wrapper classes represent primitive values as objects, while enums define a fixed collection of named constants.

In practical programming, wrapper classes are useful for processing user input, converting strings into numeric values, storing values in collections, and handling optional data. Enums are useful for representing fixed choices such as order status, payment methods, user roles, days of the week, and application settings.

Combining wrapper classes and enums allows developers to build programs with better type safety, clearer business rules, and more structured data.

2. Learning Objectives

  • Understand wrapper classes and their purpose in Java.
  • Identify all eight primitive types and their corresponding wrapper classes.
  • Apply autoboxing and unboxing in practical programs.
  • Convert strings into primitive values and wrapper objects.
  • Handle invalid numeric input using exception handling.
  • Create enums and access their constants.
  • Use enum methods such as values(), valueOf(), name(), and ordinal().
  • Combine wrapper classes and enums in real-world Java applications.

3. Understanding Wrapper Classes

3.1 Definition

A wrapper class is a class that represents a primitive data type as an object. Java provides a separate wrapper class for each of its eight primitive types.

Primitive variables store simple values directly. Wrapper objects can be used wherever Java requires reference types, including generic collections such as ArrayList<Integer>.

3.2 Primitive Types and Wrapper Classes

Primitive Type Wrapper Class Example
byte Byte Byte age = 25;
short Short Short quantity = 100;
int Integer Integer marks = 85;
long Long Long population = 100000L;
float Float Float temperature = 36.5f;
double Double Double price = 499.99;
char Character Character grade = 'A';
boolean Boolean Boolean active = true;

All eight wrapper classes are available in the java.lang package, so they do not require explicit imports.

3.3 Why Are Wrapper Classes Needed?

  • Collections: Collections such as ArrayList store objects rather than primitive values.
  • Generics: Generic type parameters require reference types, so List<Integer> is valid but List<int> is not.
  • Conversion: Wrapper classes provide methods for parsing and converting values.
  • Utility methods: Classes such as Integer provide useful constants and methods.
  • Optional values: A wrapper reference can be null when a value is absent, although null handling must be done carefully.

4. Creating and Using Wrapper Objects

4.1 Using valueOf()

The valueOf() method creates or obtains a wrapper object representing a value. It is generally preferred over explicitly creating wrapper objects with constructors, which are deprecated for these classes.

public class WrapperExample {
    public static void main(String[] args) {
        Integer number = Integer.valueOf(100);
        Double price = Double.valueOf(249.50);
        Boolean active = Boolean.valueOf(true);

        System.out.println("Number: " + number);
        System.out.println("Price: " + price);
        System.out.println("Active: " + active);
    }
}

Output:

Number: 100
Price: 249.5
Active: true

4.2 Autoboxing

Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper type.

public class AutoboxingExample {
    public static void main(String[] args) {
        int marks = 90;
        Integer studentMarks = marks;

        System.out.println("Primitive: " + marks);
        System.out.println("Wrapper: " + studentMarks);
    }
}

Output:

Primitive: 90
Wrapper: 90

In this example, Java automatically converts the primitive int value into an Integer object.

4.3 Unboxing

Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value.

public class UnboxingExample {
    public static void main(String[] args) {
        Integer total = Integer.valueOf(150);
        int amount = total;

        System.out.println("Wrapper value: " + total);
        System.out.println("Primitive value: " + amount);
    }
}

Output:

Wrapper value: 150
Primitive value: 150

Important: Unboxing a null wrapper reference causes a NullPointerException.

5. Converting Strings into Numeric Values

Programs frequently receive input as strings, even when the intended value is numeric. Wrapper classes provide parsing methods that convert valid numeric strings into primitive values.

Method Return Type Example
Integer.parseInt() int Integer.parseInt("100")
Double.parseDouble() double Double.parseDouble("25.5")
Long.parseLong() long Long.parseLong("5000")
Boolean.parseBoolean() boolean Boolean.parseBoolean("true")
Integer.valueOf() Integer Integer.valueOf("100")

Practical Example: Calculating a Total

public class StringConversionExample {
    public static void main(String[] args) {
        String quantityInput = "4";
        String priceInput = "125.50";

        int quantity = Integer.parseInt(quantityInput);
        double price = Double.parseDouble(priceInput);

        double total = quantity * price;

        System.out.println("Quantity: " + quantity);
        System.out.println("Price: " + price);
        System.out.println("Total: " + total);
    }
}

Output:

Quantity: 4
Price: 125.5
Total: 502.0

This technique is useful when reading values from text fields, configuration files, command-line arguments, or external data sources.

6. Handling Invalid Input

If a numeric string contains invalid characters, methods such as Integer.parseInt() throw a NumberFormatException. A practical program should handle this possibility instead of terminating unexpectedly.

public class SafeParsingExample {
    public static void main(String[] args) {
        String input = "12A";

        try {
            int number = Integer.parseInt(input);
            System.out.println("Number: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Invalid number. Enter digits only.");
        }
    }
}

Output:

Invalid number. Enter digits only.

Use appropriate validation before processing user input. Also remember that Boolean.parseBoolean() returns true only for a case-insensitive string equal to "true"; other strings produce false rather than a parsing exception.

7. Useful Wrapper Class Methods

Method or Constant Purpose Example
parseInt() Converts a string to a primitive integer Integer.parseInt("42")
valueOf() Obtains a wrapper object Integer.valueOf(42)
compareTo() Compares wrapper values Integer.valueOf(5).compareTo(10)
toString() Converts a value into a string representation Integer.toString(42)
MAX_VALUE Maximum value for a numeric primitive type Integer.MAX_VALUE
MIN_VALUE Minimum value for a numeric primitive type Integer.MIN_VALUE
Character.isDigit() Checks whether a character is a digit Character.isDigit('7')
Character.toUpperCase() Converts a character to uppercase Character.toUpperCase('a')

8. Understanding Enums in Java

8.1 Definition

An enum, short for enumeration, is a special Java type used to define a fixed set of named constants. It helps restrict a variable to a known set of valid choices.

For example, an order can have statuses such as PENDING, PROCESSING, SHIPPED, and DELIVERED. An enum represents these states more safely than arbitrary strings.

8.2 Declaring an Enum

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

Enum constants are conventionally written in uppercase. They can be accessed using the enum type name followed by a dot.

OrderStatus status = OrderStatus.PENDING;
System.out.println(status);

Output:

PENDING

8.3 Advantages of Enums

  • Restrict values to a predefined set of constants.
  • Improve readability and make business rules easier to understand.
  • Reduce errors caused by misspelled string values.
  • Work naturally with switch statements.
  • Support fields, constructors, and methods for richer behavior.

9. Important Enum Methods

Method Description Example
values() Returns an array of all enum constants OrderStatus.values()
valueOf() Finds a constant by its exact declared name OrderStatus.valueOf("SHIPPED")
name() Returns the declared constant name status.name()
ordinal() Returns the zero-based declaration position status.ordinal()

Note: Avoid using ordinal() as a permanent database identifier because changing the order of enum declarations changes ordinal values. Prefer explicit fields or stable string names when persistence is required.

Example: Iterating Through Enum Values

enum PaymentMethod {
    CASH,
    CARD,
    UPI,
    BANK_TRANSFER
}

public class EnumIterationExample {
    public static void main(String[] args) {
        for (PaymentMethod method : PaymentMethod.values()) {
            System.out.println(method.name());
        }
    }
}

Output:

CASH
CARD
UPI
BANK_TRANSFER

10. Using Enums with Switch Statements

Enums can be used with switch statements to select an action based on a predefined state.

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

public class OrderStatusExample {
    public static void main(String[] args) {
        OrderStatus status = OrderStatus.SHIPPED;

        switch (status) {
            case PENDING:
                System.out.println("Order is waiting for processing.");
                break;
            case PROCESSING:
                System.out.println("Order is being prepared.");
                break;
            case SHIPPED:
                System.out.println("Order is on the way.");
                break;
            case DELIVERED:
                System.out.println("Order has been delivered.");
                break;
            case CANCELLED:
                System.out.println("Order was cancelled.");
                break;
        }
    }
}

Output:

Order is on the way.

11. Combining Wrapper Classes and Enums

In practical applications, wrapper classes and enums solve different but complementary problems. Wrapper classes handle values such as amounts and quantities, while enums describe predefined categories or states.

Consider an online shopping application. The product quantity can be represented using Integer, the product price using Double, and the order status using an enum.

Practical Program: Order Management

enum OrderStatus {
    PENDING,
    PROCESSING,
    SHIPPED,
    DELIVERED,
    CANCELLED
}

public class OrderManagement {
    public static void main(String[] args) {
        Integer quantity = Integer.valueOf("3");
        Double price = Double.valueOf("199.99");
        OrderStatus status = OrderStatus.PROCESSING;

        double total = quantity * price;

        System.out.println("Quantity: " + quantity);
        System.out.println("Unit Price: " + price);
        System.out.printf("Total Amount: %.2f%n", total);
        System.out.println("Order Status: " + status);

        if (status == OrderStatus.PROCESSING) {
            System.out.println("Your order is being prepared.");
        }
    }
}

Output:

Quantity: 3
Unit Price: 199.99
Total Amount: 599.97
Order Status: PROCESSING
Your order is being prepared.

Program Explanation

  1. Integer.valueOf("3") converts the numeric string into an Integer object.
  2. Double.valueOf("199.99") converts the price string into a Double object.
  3. OrderStatus.PROCESSING assigns a valid predefined order status.
  4. Multiplication automatically unboxes the numeric wrappers to perform arithmetic.
  5. The conditional statement compares the status against a specific enum constant.

Practical note: For financial applications, use BigDecimal rather than binary floating-point types such as double when exact decimal arithmetic is required.

12. Practical Program: Student Result Management

This example uses wrapper classes to represent marks and an enum to represent the student's result category.

enum Result {
    PASS,
    FAIL
}

public class StudentResult {
    public static void main(String[] args) {
        Integer marks = Integer.valueOf("78");
        Result result;

        if (marks >= 40) {
            result = Result.PASS;
        } else {
            result = Result.FAIL;
        }

        System.out.println("Marks: " + marks);
        System.out.println("Result: " + result);
    }
}

Output:

Marks: 78
Result: PASS

The Integer object stores the marks, and the enum ensures the result is either PASS or FAIL. In a larger application, validation should also ensure that marks fall within the permitted range.

13. Practical Program: Employee Role and Bonus

Enums are helpful for representing employee roles, while wrapper classes can store a salary received as text from an external source.

enum EmployeeRole {
    DEVELOPER,
    TESTER,
    MANAGER
}

public class EmployeeBonus {
    public static void main(String[] args) {
        Double salary = Double.valueOf("40000");
        EmployeeRole role = EmployeeRole.DEVELOPER;
        double bonusRate;

        switch (role) {
            case DEVELOPER:
                bonusRate = 0.10;
                break;
            case TESTER:
                bonusRate = 0.08;
                break;
            case MANAGER:
                bonusRate = 0.15;
                break;
            default:
                bonusRate = 0.0;
        }

        double bonus = salary * bonusRate;

        System.out.println("Role: " + role);
        System.out.printf("Salary: %.2f%n", salary);
        System.out.printf("Bonus: %.2f%n", bonus);
    }
}

Output:

Role: DEVELOPER
Salary: 40000.00
Bonus: 4000.00

14. Practical Program: Enum with Fields and Methods

An enum can contain fields, a constructor, and methods. This is useful when each constant needs associated information.

enum Priority {
    LOW(1),
    MEDIUM(2),
    HIGH(3);

    private final int level;

    Priority(int level) {
        this.level = level;
    }

    public int getLevel() {
        return level;
    }
}

public class PriorityExample {
    public static void main(String[] args) {
        Priority priority = Priority.HIGH;

        System.out.println("Priority: " + priority);
        System.out.println("Level: " + priority.getLevel());
    }
}

Output:

Priority: HIGH
Level: 3

The constructor is invoked internally when the enum constants are created. It cannot be called directly using the new keyword.

15. Practical Program: Validating an Enum from User Input

The valueOf() method requires an exact enum constant name. For example, "CASH" is valid, but "cash" does not match by default. Input can be normalized before conversion.

enum PaymentMethod {
    CASH,
    CARD,
    UPI
}

public class PaymentValidation {
    public static void main(String[] args) {
        String input = "upi";

        try {
            PaymentMethod method =
                PaymentMethod.valueOf(input.trim().toUpperCase());

            System.out.println("Selected payment: " + method);
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid payment method.");
        }
    }
}

Output:

Selected payment: UPI

In production applications, also validate that the input is not null before calling methods on it. A null input would cause a NullPointerException.

16. Wrapper Classes vs. Enums

Feature Wrapper Classes Enums
Primary purpose Represent primitive values as objects Represent a fixed set of named constants
Examples Integer, Double, Boolean OrderStatus, PaymentMethod
Typical values Numbers, characters, Boolean values Predefined categories and states
Conversion Supports parsing, boxing, and unboxing Supports lookup through valueOf()
Nullability Wrapper references may be null Variables of enum types may also be null
Common use Collections, numeric input, optional numeric values Statuses, roles, categories, fixed options

17. Common Errors and How to Avoid Them

Error Reason Solution
NumberFormatException Invalid numeric string Validate input and handle parsing exceptions.
NullPointerException Unboxing a null wrapper Check for null before unboxing.
IllegalArgumentException Unknown name passed to enum valueOf() Validate or normalize input and handle invalid names.
Using == for wrapper value comparison It may compare object references Use equals() or compare primitive values safely.
Using enum ordinal as a permanent ID Declaration order may change Use an explicit stable identifier.
Unexpected floating-point total Binary floating-point precision Use BigDecimal for exact decimal financial calculations.

18. Best Practices

  • Use primitive types for simple calculations when object behavior is unnecessary.
  • Use wrapper types when working with collections, generics, or APIs that require objects.
  • Prefer valueOf() and parsing methods over deprecated wrapper constructors.
  • Validate external data before converting it into numeric or enum values.
  • Use enums instead of repeated string literals for a fixed set of choices.
  • Compare enum constants directly with ==; enum constants are unique instances.
  • Use equals() for wrapper object value comparison when null handling is addressed.
  • Avoid unboxing nullable wrapper objects without checking them.
  • Do not use enum ordinal positions as stable database identifiers.
  • Keep variable names, enum constants, and methods descriptive and consistent.

19. Practice Exercises

  1. Temperature Converter: Convert a temperature supplied as a string into a numeric wrapper value and calculate its Fahrenheit equivalent.
  2. Library Management: Create a BookStatus enum with AVAILABLE, ISSUED, and RESERVED constants.
  3. Shopping Cart: Use Integer for quantity and Double for unit price to calculate the total.
  4. Employee Management: Create an EmployeeRole enum and calculate a role-based bonus.
  5. Input Validation: Parse a string into an integer and handle invalid input with try-catch.
  6. Payment Selection: Accept a payment method as text and convert it safely into a PaymentMethod enum constant.
  7. Student Grading: Convert marks into an Integer and assign an enum representing a grade category.

20. Mini Project: Product Inventory System

Project Requirements

  • Store a product name, quantity, and price.
  • Use wrapper classes for quantity and price.
  • Use an enum for product availability.
  • Calculate the inventory value.
  • Display product details and status.
enum Availability {
    IN_STOCK,
    OUT_OF_STOCK
}

public class ProductInventory {
    public static void main(String[] args) {
        String productName = "Keyboard";
        Integer quantity = Integer.valueOf("5");
        Double price = Double.valueOf("799.50");

        Availability availability =
            quantity > 0
                ? Availability.IN_STOCK
                : Availability.OUT_OF_STOCK;

        double inventoryValue = quantity * price;

        System.out.println("Product: " + productName);
        System.out.println("Quantity: " + quantity);
        System.out.printf("Unit Price: %.2f%n", price);
        System.out.printf("Inventory Value: %.2f%n", inventoryValue);
        System.out.println("Availability: " + availability);
    }
}

Output:

Product: Keyboard
Quantity: 5
Unit Price: 799.50
Inventory Value: 3997.50
Availability: IN_STOCK

Project Extension Ideas

  • Read quantity and price from user input.
  • Handle invalid numbers and negative quantities.
  • Add an enum for product categories.
  • Store multiple products in an ArrayList.
  • Generate a low-stock warning when the quantity is below a chosen threshold.

21. Interview Questions and Answers

Q1. What is a wrapper class in Java?

A wrapper class represents a primitive data type as an object. For example, Integer is the wrapper for int.

Q2. What is autoboxing?

Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper type, such as assigning an int to an Integer variable.

Q3. What is unboxing?

Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value.

Q4. Why are wrapper classes used with collections?

Java generic collections use reference types rather than primitive types, so an ArrayList of integers is declared as ArrayList<Integer>.

Q5. What happens when an invalid string is passed to Integer.parseInt()?

Java throws a NumberFormatException.

Q6. What is an enum?

An enum is a special Java type that defines a fixed set of named constants.

Q7. What does values() do?

The values() method returns an array containing the enum constants in their declaration order.

Q8. What does valueOf() do in an enum?

It returns the enum constant matching the specified name exactly, or throws an IllegalArgumentException if no matching constant exists.

Q9. Can an enum contain fields and methods?

Yes. An enum can define fields, a constructor, and methods to associate additional information or behavior with its constants.

Q10. Why should ordinal() not be used as a permanent identifier?

Its value depends on the constant's declaration position, which may change when the enum is modified.

Q11. What is the difference between Integer and int?

int is a primitive type, whereas Integer is its object wrapper and can represent an absent value using null.

Q12. How do wrapper classes and enums work together?

Wrapper classes represent values such as quantities or marks, while enums represent predefined choices such as order status, payment type, or employee role.

22. Quick Revision Checklist

  • Know all eight primitive and wrapper type pairs.
  • Understand autoboxing and unboxing.
  • Use parsing methods to convert valid strings into numeric values.
  • Handle invalid input and nullable wrapper references safely.
  • Declare enum constants using the enum keyword.
  • Understand values(), valueOf(), name(), and ordinal().
  • Apply enums in switch statements and practical business rules.
  • Combine wrapper classes and enums in inventory, order, student, and employee programs.

23. Conclusion

Wrapper classes and enums are useful Core Java features that help developers represent data more effectively. Wrapper classes support object-based operations, numeric conversion, and collection usage. Enums represent predefined choices in a type-safe and readable way.

By combining these features in practical programs such as student result management, employee bonus calculation, order processing, and product inventory, developers can write clearer and more maintainable Java applications. Regular coding practice will help reinforce these concepts and prepare learners for Core Java projects and technical interviews.

24. Learn More with JustAcademy

Continue learning Java fundamentals, object-oriented programming, exception handling, collections, and other Core Java concepts through the course resources below.

Previous Next
whatsapp