WikiGalaxy

Personalize

Java Wrapper Classes

Introduction to Wrapper Classes:

Wrapper classes in Java are used to convert primitive data types into objects. This is particularly useful when you need to use primitives in collections that only accept objects.

Example 1: Integer Wrapper Class

The Integer class wraps a value of the primitive type int in an object.


      Integer myInt = Integer.valueOf(5);
      int num = myInt.intValue();
      

Autoboxing and Unboxing

Java automatically converts between primitive types and their corresponding wrapper classes, known as autoboxing and unboxing.


      Integer myInt = 10; // Autoboxing
      int num = myInt;    // Unboxing
      

Example 2: Double Wrapper Class

Double is a wrapper class for the primitive type double, allowing double values to be treated as objects.


      Double myDouble = Double.valueOf(10.5);
      double d = myDouble.doubleValue();
      

Example 3: Character Wrapper Class

Character class wraps a value of the primitive type char in an object.


      Character myChar = Character.valueOf('A');
      char ch = myChar.charValue();
      

Example 4: Boolean Wrapper Class

The Boolean class wraps a value of the primitive type boolean in an object.


      Boolean myBool = Boolean.valueOf(true);
      boolean b = myBool.booleanValue();
      

Advanced Wrapper Class Usage

Example 5: Byte Wrapper Class

The Byte class wraps a value of the primitive type byte in an object.


      Byte myByte = Byte.valueOf((byte)10);
      byte b = myByte.byteValue();
      

Example 6: Short Wrapper Class

The Short class wraps a value of the primitive type short in an object.


      Short myShort = Short.valueOf((short)100);
      short s = myShort.shortValue();
      

Example 7: Long Wrapper Class

The Long class wraps a value of the primitive type long in an object.


      Long myLong = Long.valueOf(100000L);
      long l = myLong.longValue();
      

Example 8: Float Wrapper Class

The Float class wraps a value of the primitive type float in an object.


      Float myFloat = Float.valueOf(5.75f);
      float f = myFloat.floatValue();
      

Example 9: Parsing Strings to Primitives

Wrapper classes provide methods to parse strings into primitive data types.


      int num = Integer.parseInt("123");
      

Example 10: Comparing Wrapper Objects

Wrapper classes provide methods for comparing objects.


      Integer a = Integer.valueOf(10);
      Integer b = Integer.valueOf(20);
      int result = a.compareTo(b);
      
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025