Java Wrapper Classes


Java Wrapper Classes

Folder classes provide a way to use older data types (int, boolean, etc ..) as objects.

The table below shows the classic type and equivalent folding category:


Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Sometimes you should use folding classes, for example when working with collection items, such as ArrayList, where older types can be used (the list can only store items):


Example
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
        

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
        


Creating Wrapper Objects

To create a folding object, use a wrapper section instead of the old type. To get value, you can simply print an item:


Example
public class Main {
            public static void main(String[] args) {
              Integer myInt = 5;
              Double myDouble = 5.99;
              Character myChar = 'A';
              System.out.println(myInt);
              System.out.println(myDouble);
              System.out.println(myChar);
            }
          }
          


Now that you are working on things, you can use certain methods to get information about something.

For example, the following methods are used to find the value associated with a corresponding fold: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue().

This example will produce the same result as the example above:


Example
public class Main {
            public static void main(String[] args) {
              Integer myInt = 5;
              Double myDouble = 5.99;
              Character myChar = 'A';
              System.out.println(myInt.intValue());
              System.out.println(myDouble.doubleValue());
              System.out.println(myChar.charValue());
            }
          }
          

Another useful method is the toString() method, which is used to convert folding objects into strings.

In the following example, we convert Integer to String, and use the String class length() to extract the "string" length:


Example
public class Main {
            public static void main(String[] args) {
              Integer myInt = 100;
              String myString = myInt.toString();
              System.out.println(myString.length());
            }
          }