Wrapper Classes
Home ] Up ] What is a Class? ] What is an Instance? ] Class Members ] Methods and Overloading ] Instance Creation ] Instance Destruction ] Finalizers ] Class Variables and Methods ] [ Wrapper Classes ]

 

Passing Arguments
Returning Values
Autoboxing

 

Sometimes it is necessary to pass a primitive type when a (reference to an) object is expected.

For example, assume that you have a method that specifies that one of its arguments is of type Object, and you need to pass it an int:

package example;

public class PassIntTest
{
  public static void handleValue(Object value)
  {
    // Do something with value...
  }

  public static void main(String[] args)
  {
    int intValue = 56;
    handleValue(intValue); // Error
  }
}

Prior to JSDK 5.0, the above code will produce a compile-time error:

"PassIntTest.java": cannot find symbol; symbol : method valueOf(int), location:
    class java.lang.Integer at line 13, column 17
"PassIntTest.java": Fatal Error: Unable to find method valueOf

 

The solution is to use a Wrapper class.  For every primitive data type, there is a corresponding wrapper class:

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

Each wrapper class has a constructor which accepts a primitive type value.  For example:

Integer intWrapper = new Integer(56);

The resulting instance "wraps" the supplied value.

Note:

  •  Each wrapper class is immutable;  that is, once the value has been wrapped, it may not be changed.
  •  Each wrapper class is final;  that is, it may not be extended.

This page was last modified on 02 October, 2007