Popular Searches
Popular Course Categories
Popular Courses

Understanding Integer, Double, Boolean, Character, and Other Wrappers

Understanding Integer, Double, Boolean, Character, and Other Wrappers

Wrapper Classes, Autoboxing, and Enumerations

Understanding Integer, Double, Boolean, Character, and Other Wrapper Classes in Java

Course: Core Java Training

Topic: Understanding Integer, Double, Boolean, Character, and Other Wrapper Classes

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy Official Website


1. Introduction to Wrapper Classes in Java

Java provides eight primitive data types: byte, short, int, long, float, double, char, and boolean. These types are used to store simple values such as numbers, characters, and logical states.

Primitive data types are not objects, so they cannot directly use object methods or serve as generic type arguments. Java provides wrapper classes that represent primitive values as objects. These classes belong to the java.lang package, which is imported automatically.

For example, int stores an integer value, while Integer is its corresponding wrapper class. Similarly, double corresponds to Double, boolean corresponds to Boolean, and char corresponds to Character.

Why Are Wrapper Classes Important?

  • They allow primitive values to be represented as objects.
  • They make primitive values usable in collections such as ArrayList.
  • They provide methods for converting strings into numeric or logical values.
  • They support automatic conversion through autoboxing and unboxing.
  • They provide useful constants and utility methods.
  • They allow reference variables to hold null, representing the absence of a value.

2. Primitive Data Types and Their Wrapper Classes

Each Java primitive type has a corresponding wrapper class, except that void has the special non-instantiable class Void rather than an ordinary value wrapper.

Primitive Type Wrapper Class Example Purpose
byte Byte Byte age = 25; Stores a small integer value.
short Short Short count = 100; Stores a short integer value.
int Integer Integer marks = 85; Represents an integer object.
long Long Long population = 8000000L; Represents a large integer value.
float Float Float rating = 4.5f; Represents a single-precision decimal value.
double Double Double price = 99.99; Represents a double-precision decimal value.
char Character Character grade = 'A'; Represents a character object.
boolean Boolean Boolean active = true; Represents a true or false value.

Important: The wrapper classes Integer and Character have different names from their primitive types. Most of the other wrapper class names are formed by capitalizing the primitive type's first letter.

3. Understanding the Integer Class

The Integer class is the wrapper class for the primitive int type. It represents a 32-bit signed integer as an object and provides methods for parsing strings, converting values, comparing integers, and finding the minimum and maximum supported values.

3.1 Declaring Integer Variables

public class IntegerExample {
    public static void main(String[] args) {
        int primitiveNumber = 100;
        Integer wrapperNumber = 200;

        System.out.println("Primitive: " + primitiveNumber);
        System.out.println("Wrapper: " + wrapperNumber);
    }
}

Output:

Primitive: 100
Wrapper: 200

The variable primitiveNumber stores an int value, while wrapperNumber refers to an Integer object.

3.2 Important Integer Methods

Method or Constant Description Example
Integer.parseInt() Converts a numeric string to primitive int. Integer.parseInt("123")
Integer.valueOf() Returns an Integer representing a value or parsed string. Integer.valueOf("123")
Integer.toString() Converts an integer value to a string. Integer.toString(123)
Integer.compare() Compares two integer values. Integer.compare(10, 20)
Integer.MAX_VALUE Provides the largest supported int value. 2147483647
Integer.MIN_VALUE Provides the smallest supported int value. -2147483648

3.3 Converting a String into an Integer

public class ParseIntegerExample {
    public static void main(String[] args) {
        String text = "250";
        int number = Integer.parseInt(text);

        System.out.println(number + 50);
    }
}

Output:

300

The method parseInt() converts the string "250" into the primitive integer 250. The resulting value can be used in arithmetic operations.

If the string does not contain a valid integer in the expected format, parseInt() throws a NumberFormatException.

3.4 Comparing Integer Values

public class IntegerCompareExample {
    public static void main(String[] args) {
        Integer first = 100;
        Integer second = 200;

        System.out.println(first.compareTo(second));
        System.out.println(first.equals(100));
    }
}

Output:

-1
true

compareTo() returns a negative value when the first value is smaller, zero when they are equal, and a positive value when the first value is larger. The equals() method compares the wrapped integer values.

4. Understanding the Double Class

The Double class is the wrapper class for the primitive double type. It represents a 64-bit floating-point value and provides methods for parsing decimal strings, converting values, and checking special floating-point values.

4.1 Declaring Double Variables

public class DoubleExample {
    public static void main(String[] args) {
        double primitivePrice = 149.75;
        Double wrapperPrice = 299.50;

        System.out.println("Primitive price: " + primitivePrice);
        System.out.println("Wrapper price: " + wrapperPrice);
    }
}

Output:

Primitive price: 149.75
Wrapper price: 299.5

The value 299.50 is printed as 299.5 because trailing zeros are not necessarily displayed when a floating-point value is converted to text.

4.2 Important Double Methods

Method or Constant Description Example
Double.parseDouble() Converts a numeric string to primitive double. Double.parseDouble("12.5")
Double.valueOf() Returns a Double value from a number or numeric string. Double.valueOf("12.5")
Double.toString() Converts a double value to a string. Double.toString(12.5)
Double.isNaN() Checks whether a value is NaN (Not a Number). Double.isNaN(value)
Double.isInfinite() Checks whether a value is positive or negative infinity. Double.isInfinite(value)
Double.MAX_VALUE Largest finite positive double value. Double.MAX_VALUE

4.3 Converting a String into a Double

public class ParseDoubleExample {
    public static void main(String[] args) {
        String text = "125.75";
        double amount = Double.parseDouble(text);

        System.out.println(amount + 10.25);
    }
}

Output:

136.0

Use Double.parseDouble() when a numeric string needs to become a primitive decimal value. For financial calculations requiring exact decimal arithmetic, consider BigDecimal instead of relying on binary floating-point values.

5. Understanding the Boolean Class

The Boolean class is the wrapper class for the primitive boolean type. It represents one of two logical values: true or false.

5.1 Declaring Boolean Variables

public class BooleanExample {
    public static void main(String[] args) {
        boolean primitiveStatus = true;
        Boolean wrapperStatus = false;

        System.out.println(primitiveStatus);
        System.out.println(wrapperStatus);
    }
}

Output:

true
false

5.2 Important Boolean Methods

Method or Constant Description
Boolean.parseBoolean() Returns primitive true when the string equals "true", ignoring case; otherwise returns false.
Boolean.valueOf() Returns a Boolean representing a Boolean value or parsed string.
Boolean.toString() Converts a Boolean value to its text representation.
Boolean.TRUE Constant representing true.
Boolean.FALSE Constant representing false.

5.3 Converting Strings into Boolean Values

public class ParseBooleanExample {
    public static void main(String[] args) {
        String firstText = "true";
        String secondText = "FALSE";
        String invalidText = "yes";

        System.out.println(Boolean.parseBoolean(firstText));
        System.out.println(Boolean.parseBoolean(secondText));
        System.out.println(Boolean.parseBoolean(invalidText));
    }
}

Output:

true
false
false

Important: Boolean.parseBoolean() does not validate arbitrary words. A string such as "yes" produces false, not an exception. If your application accepts inputs such as yes/no or 1/0, implement explicit validation.

6. Understanding the Character Class

The Character class is the wrapper class for the primitive char type. It provides methods for checking and working with individual UTF-16 code units, including character classification and case conversion.

6.1 Declaring Character Variables

public class CharacterExample {
    public static void main(String[] args) {
        char primitiveLetter = 'A';
        Character wrapperLetter = 'b';

        System.out.println(primitiveLetter);
        System.out.println(wrapperLetter);
    }
}

Output:

A
b

6.2 Important Character Methods

Method Description Example
Character.isLetter() Checks whether a character is a letter. Character.isLetter('A')
Character.isDigit() Checks whether a character is a digit. Character.isDigit('7')
Character.isWhitespace() Checks whether a character is whitespace. Character.isWhitespace(' ')
Character.isUpperCase() Checks whether a character is uppercase. Character.isUpperCase('A')
Character.isLowerCase() Checks whether a character is lowercase. Character.isLowerCase('a')
Character.toUpperCase() Converts a character to uppercase where applicable. Character.toUpperCase('b')
Character.toLowerCase() Converts a character to lowercase where applicable. Character.toLowerCase('A')

6.3 Character Classification Example

public class CharacterMethodsExample {
    public static void main(String[] args) {
        char letter = 'A';
        char digit = '5';
        char space = ' ';

        System.out.println(Character.isLetter(letter));
        System.out.println(Character.isDigit(digit));
        System.out.println(Character.isWhitespace(space));
        System.out.println(Character.toLowerCase(letter));
    }
}

Output:

true
true
true
a

Note: Java's char represents a UTF-16 code unit, not always a complete Unicode character. Some Unicode characters require two char values, so full Unicode text processing may require code-point methods such as Character.codePointAt().

7. Understanding Other Wrapper Classes

Besides Integer, Double, Boolean, and Character, Java provides Byte, Short, Long, and Float.

7.1 Byte Class

The Byte class wraps the primitive byte, an 8-bit signed integer with a range from -128 to 127.

public class ByteExample {
    public static void main(String[] args) {
        Byte value = Byte.valueOf((byte) 100);
        System.out.println(value);
        System.out.println(Byte.MAX_VALUE);
    }
}

Output:

100
127

7.2 Short Class

The Short class wraps the primitive short, a 16-bit signed integer.

public class ShortExample {
    public static void main(String[] args) {
        Short value = Short.valueOf((short) 2000);
        System.out.println(value);
        System.out.println(Short.MIN_VALUE);
    }
}

Output:

2000
-32768

7.3 Long Class

The Long class wraps the primitive long, a 64-bit signed integer. Use the suffix L for long literals when needed.

public class LongExample {
    public static void main(String[] args) {
        Long population = 8000000000L;
        System.out.println(population);
        System.out.println(Long.MAX_VALUE);
    }
}

Output:

8000000000
9223372036854775807

7.4 Float Class

The Float class wraps the primitive float, a 32-bit floating-point type. Use the suffix f for float literals.

public class FloatExample {
    public static void main(String[] args) {
        Float rating = 4.5f;
        System.out.println(rating);
        System.out.println(Float.MAX_VALUE);
    }
}

Output:

4.5
3.4028235E38

8. Autoboxing and Unboxing

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

8.1 Autoboxing Example

public class AutoboxingExample {
    public static void main(String[] args) {
        int number = 50;
        Integer objectNumber = number;

        System.out.println(objectNumber);
    }
}

Output:

50

The compiler automatically converts the primitive int value into an Integer object.

8.2 Unboxing Example

public class UnboxingExample {
    public static void main(String[] args) {
        Integer objectNumber = 75;
        int number = objectNumber;

        System.out.println(number + 25);
    }
}

Output:

100

The compiler automatically extracts the primitive integer value from the wrapper object.

8.3 Null and Unboxing

public class NullUnboxingExample {
    public static void main(String[] args) {
        Integer value = null;

        // This statement throws NullPointerException.
        // int number = value;
        System.out.println("A null wrapper cannot be unboxed safely.");
    }
}

A wrapper variable can contain null, but attempting to unbox it causes a NullPointerException. Check for null before unboxing when the value may be absent.

9. Using Wrapper Classes with Collections

Java generic collections work with reference types rather than primitive type arguments. Wrapper classes allow primitive-like values to be stored in collections such as ArrayList.

import java.util.ArrayList;

public class IntegerListExample {
    public static void main(String[] args) {
        ArrayList<Integer> marks = new ArrayList<>();

        marks.add(85);
        marks.add(90);
        marks.add(78);

        int total = 0;

        for (Integer mark : marks) {
            total += mark;
        }

        System.out.println("Marks: " + marks);
        System.out.println("Total: " + total);
    }
}

Output:

Marks: [85, 90, 78]
Total: 253

The calls to add() use autoboxing, and the enhanced for loop unboxes each value when adding it to the primitive variable total.

10. Converting Between Strings and Wrapper Values

Wrapper classes provide useful methods for converting textual input into values and converting values into text.

Requirement Recommended Method Example
String to primitive integer Integer.parseInt() Integer.parseInt("42")
String to Integer object Integer.valueOf() Integer.valueOf("42")
String to primitive decimal Double.parseDouble() Double.parseDouble("19.95")
String to Boolean value Boolean.parseBoolean() Boolean.parseBoolean("true")
Primitive integer to String Integer.toString() Integer.toString(42)
Primitive decimal to String Double.toString() Double.toString(19.95)

Example program:

public class WrapperConversionExample {
    public static void main(String[] args) {
        String ageText = "25";
        String salaryText = "45000.75";

        int age = Integer.parseInt(ageText);
        double salary = Double.parseDouble(salaryText);

        String ageResult = Integer.toString(age);
        String salaryResult = Double.toString(salary);

        System.out.println(age + 1);
        System.out.println(salary + 1000);
        System.out.println(ageResult);
        System.out.println(salaryResult);
    }
}

Output:

26
46000.75
25
45000.75

11. Primitive Types vs Wrapper Classes

Feature Primitive Type Wrapper Class
Example int number = 10; Integer number = 10;
Type category Primitive Reference type
Can be null No Yes
Has object methods No Yes
Can be a generic type argument No Yes
Memory and performance Usually lower overhead Usually higher overhead
Useful for Simple calculations and local values Collections, nullable values, and conversion utilities

Wrapper classes are immutable: once a wrapper object is created, its contained value cannot be changed. Assigning a different value to a wrapper variable makes the variable refer to another value object; it does not modify the original object.

12. Comparing Wrapper Objects Correctly

One common mistake is using == to compare wrapper objects. For reference types, == checks whether two references identify the same object. Use equals() to compare wrapped values.

public class WrapperComparisonExample {
    public static void main(String[] args) {
        Integer first = Integer.valueOf(1000);
        Integer second = Integer.valueOf(1000);

        System.out.println(first == second);
        System.out.println(first.equals(second));
    }
}

Output:

false
true

For these separately obtained values, the references are different even though the integer values are equal. Do not rely on wrapper reference identity, even for values that may be cached. Use equals() or compare unboxed primitive values when appropriate.

13. Common Mistakes and How to Avoid Them

Mistake Why It Is a Problem Correct Approach
Using == to compare wrapper values It may compare object identity rather than value. Use equals() for value comparison.
Unboxing a null wrapper It throws NullPointerException. Check for null before unboxing.
Parsing invalid numeric text It can throw NumberFormatException. Validate input and handle parsing errors.
Using Boolean.parseBoolean("yes") It returns false rather than interpreting yes as true. Define explicit rules for accepted inputs.
Using wrappers for every calculation It can add unnecessary memory and conversion overhead. Prefer primitives for ordinary calculations.
Using double for exact financial values Binary floating-point cannot represent every decimal fraction exactly. Consider BigDecimal for exact decimal calculations.
Assuming Character handles every Unicode symbol as one char Some Unicode code points require two UTF-16 code units. Use code-point-aware methods when necessary.

14. Best Practices for Wrapper Classes

  • Use primitive types for routine arithmetic when a nullable object is not needed.
  • Use wrapper classes when working with generic collections, APIs requiring objects, or optional numeric values.
  • Prefer parseInt(), parseDouble(), and similar parsing methods when a primitive result is required.
  • Prefer valueOf() when a wrapper object is required.
  • Check for null before unboxing wrapper variables that may not contain a value.
  • Use equals() for wrapper value comparisons.
  • Handle invalid user input instead of assuming every string can be converted.
  • Remember that numeric wrapper classes are immutable.
  • Use BigDecimal for calculations requiring exact decimal arithmetic, such as many monetary calculations.

15. Practical Exercise: Student Information Processor

Create a Java program that stores a student's age as an Integer, percentage as a Double, active status as a Boolean, and grade as a Character. Print the values, parse the age from a string, and check whether the grade is uppercase.

public class StudentWrapperExercise {
    public static void main(String[] args) {
        String ageText = "21";

        Integer age = Integer.valueOf(ageText);
        Double percentage = 87.5;
        Boolean active = true;
        Character grade = 'A';

        System.out.println("Age: " + age);
        System.out.println("Percentage: " + percentage);
        System.out.println("Active: " + active);
        System.out.println("Grade: " + grade);
        System.out.println("Uppercase grade: "
                + Character.isUpperCase(grade));
    }
}

Expected Output:

Age: 21
Percentage: 87.5
Active: true
Grade: A
Uppercase grade: true

Practice Questions

  1. Write a program that converts a string into an integer and calculates its square.
  2. Use Double.parseDouble() to convert a decimal string and calculate a 10% increase.
  3. Convert the string "TRUE" into a Boolean value.
  4. Check whether a character is a digit, a letter, or whitespace.
  5. Create an ArrayList<Integer> and calculate the sum of its elements.
  6. Demonstrate the difference between == and equals() with two wrapper objects.
  7. Handle invalid numeric input using a try-catch block.

16. Interview Questions and Answers

Q1. What is a wrapper class in Java?

A wrapper class represents a primitive value as an object and provides methods and constants for working with that value.

Q2. Name the wrapper class for int and char.

The wrapper classes are Integer for int and Character for char.

Q3. What is autoboxing?

Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper object, such as converting int to Integer.

Q4. What is unboxing?

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

Q5. What is the difference between parseInt() and valueOf()?

Integer.parseInt("123") returns the primitive int value 123, while Integer.valueOf("123") returns an Integer object.

Q6. Why can wrapper variables contain null?

Wrapper classes are reference types, so their variables can refer to an object or contain null. Primitive variables cannot contain null.

Q7. Why should equals() be used instead of == for wrappers?

equals() compares the wrapped values, whereas == compares references when used with wrapper objects.

Q8. What happens when an invalid number is passed to Integer.parseInt()?

The method throws a NumberFormatException if the input is not a valid integer representation.

Q9. Can primitive types be used in ArrayList?

No. Java generic collections use reference types, so use ArrayList<Integer> instead of ArrayList<int>.

Q10. Are wrapper objects mutable?

No. Wrapper classes such as Integer, Double, Boolean, and Character are immutable.

17. Quick Revision Checklist

  • Understand the purpose of wrapper classes.
  • Remember all eight primitive-to-wrapper mappings.
  • Know the uses of Integer, Double, Boolean, and Character.
  • Practice string conversion using parseInt() and parseDouble().
  • Understand autoboxing and unboxing.
  • Avoid unboxing null values.
  • Use wrapper classes with generic collections.
  • Use equals() to compare wrapper values.
  • Handle invalid input and numeric precision carefully.

18. Conclusion

Wrapper classes are an important part of Core Java because they connect primitive values with Java's object-oriented features. Integer, Double, Boolean, Character, Byte, Short, Long, and Float provide useful methods for conversion, comparison, and value handling. Understanding autoboxing, unboxing, null safety, collections, and correct value comparison helps you write reliable Java applications.

To continue learning Java fundamentals, explore the JustAcademy Core Java Training Course, register for a course demo, or visit the JustAcademy website.

Previous Next
whatsapp