Wrapper Class in Java
- In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive Java types.
- That is, for each primitive type, there is a corresponding Java “Wrapper” class that represents that type.
- e.g. the wrapper for the int type is the Integer class.
- Wrapper Classes are based upon the well-known software engineering design pattern called the Wrapper pattern.
- A design pattern is a template solution to a common problem. It describes the problem and identifies the recommended solution(s) to that problem.
- Because design patterns deal with common problems, they are often quite abstract!
- Some code (the client) needs a class to use a certain interface (which it does not use)
- The problem:
- e.g. we want to store an int in a Vector, but Vectors do not accept primitive types.
- The Solution:
- We create another class that wraps the underlying class/type and provides an appropriate interface for the client.
- e.g. we create an Integer class that subclasses Object (as all classes do), allowing us to store wrapped int’s in Vectors.
Java Wrapper Classes
Some Useful Methods
- The Java Wrapper Classes include various useful methods:
–Getting a value from a String
e.g. int value = Integer.parseInt(“33”);
sets value to 33.
–
–Converting a value to a String:
e.g. String str = Double.toString(33.34);
sets str to the String “33.34”.
–
Getting a wrapper class instance for a value:
e.g. Integer obj = Integer.getInteger(“12”);
–Getting the maximum permitted int value
e.g. int value = Integer.MAX_VALUE;
sets value to 2147483647.
–
–Getting the minimum permitted int value
e.g. int value = Integer.MIN_VALUE;
sets value to -2147483647.
–
–Getting the value in an Integer object
e.g. int value = new Integer(545).intValue();
sets value to 545.