Wrapper classes

Wrapper classes and associated methods
The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper classes are found in the Java API documentation.
Method Purpose
parseInt(s) returns a signed decimal integer value equivalent to string s
toString(i) returns a new String object representing the integer i
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as an double
floatValue() returns the value of this Integer as a float
intValue() returns the value of this Integer as an int
shortValue() returns the value of this Integer as a short
longValue() returns the value of this Integer as a long
int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0 if the values are equal. Returns a negative value if the invoking object has a lower value. Returns a positive value if the invoking object has a greater value.
static int compare(int num1, int num2) Compares the values of num1 and num2. Returns 0 if the values are equal. Returns a negative value if num1 is less than num2. Returns a positive value if num1 is greater than num2.
boolean equals(Object intObj) Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it returns false.

Auto boxing and auto unboxing
When Java automatically converts a primitive type like int into corresponding wrapper class object e.g. Integer than its called autoboxing because primitive is boxed into wrapper class while in opposite case is called unboxing, where an Integer object is converted into primitive int. All primitive types e.g. byte, short, char, int, long, float, double and boolean has corresponding wrapper class e.g. Byte, Short, Integer, Character etc and participate in autoboxing and unboxing. Since whole process happens automatically without writing any code for conversion its called autoboxing and auto unboxing.
* Compiler uses valueOf() method to convert primitive to Object and uses intValue(), doubleValue() etc to get primitive value from Object.
* During autoboxing boolean is converted to Boolean, byte to Byte, char converted to Character, float changes to Float, int goes to Integer, long goes to Long and short converts to Short, while in unboxing opposite happens like Float to float.
Example: - public class AutoboxingTest {
public static void main(String args[]) {
// Example 1: == comparison pure primitive – no autoboxing
int i1 = 1;
int i2 = 1;
System.out.println("i1==i2 : " + (i1 == i2)); // true
// Example 2: equality operator mixing object and primitive
Integer num1 = 1; // autoboxing
int num2 = 1;
System.out.println("num1 == num2 : " + (num1 == num2)); // true
// Example 3: special case - arises due to autoboxing in Java
Integer obj1 = 1; // autoboxing will call Integer.valueOf()
Integer obj2 = 1; // same call to Integer.valueOf() will return same
// cached Object
System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
// Example 4: equality operator - pure object comparison
Integer one = new Integer(1); // no autoboxing
Integer anotherOne = new Integer(1);
System.out.println("one == anotherOne : " + (one == anotherOne)); // false
}
}
Output: -
C:\java>javac AutoboxingTest.java
C:\java>java AutoboxingTest
i1==i2 : true
num1 == num2 : true
obj1 == obj2 : true
one == anotherOne : false
Things to remember while using autoboxing in Java
1. Comparing Objects with equality Operator
2. Mixing object and primitive in equality and relational operator
3. Cached Objects
4. Unnecessary objects and Garbage Collection overhead
autoboxing and unboxing in Java are great convenience but demands care and awareness while using them. autoboxing and unboxing has several legitimate use case but should not be used with equality operator specially mixing with primitive and object is dangerous.
Conversion between data types
The wrapper classes also provide methods which can be used to convert a String to any of the primitive data types, except character. All these methods are static. These methods have the format parse*() where * refers to any of the primitive data types except char. And to convert any of the primitive data type value to a String, we use the valueOf() methods of the String class which through method overloading and implicit casting can accept any of the eight primitive types.
int x = Integer.parseInt("34"); // x=34
double y = Double.parseDouble("34.7"); // y =34.7
String s1= String.valueOf('a'); // s1="a"
String s2=String.valueOf(true); // s2="true"
Using java.util package
The package java.util contains a number of useful classes and interfaces. Although the name of the package might imply that these are utility classes, they are really more important than that. In fact, Java depends directly on several of the classes in this package, and many programs will find these classes indispensable. The classes and interfaces in java.util include:
* The Hashtable class for implementing hashtables, or associative arrays.
* The Vector class, which supports variable-length arrays.
* The Enumeration interface for iterating through a collection of elements.
* The StringTokenizer class for parsing strings into distinct tokens separated by delimiter characters.
* The EventObject class and the EventListener interface, which form the basis of the new AWT event model in Java 1.1.
* The Locale class in Java 1.1, which represents a particular locale for internationalization purposes.
* The Calendar and TimeZone classes in Java. These classes interpret the value of a Date object in the context of a particular calendar system.
* The ResourceBundle class and its subclasses, ListResourceBundle and PropertyResourceBundle, which represent sets of localized data in Java 1.1.

The Utility Package of Java consist of the following components:
1. Collections framework: - The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.
A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.
The classes and interfaces of the collections framework are in package java.util.
2. Legacy collection classes: - Legacy classes and interfaces are the classes and interfaces that formed the collections framework in the earlier versions of Java and how now been restructured or re-engineered. They are fully compatible with the framework.The legacy classes defined by java.util package are Dictionary, Hashtable, Properties, Stack and Vector.
3. Event model: - The goal of the event driven programming is to make an application respond to user generated events such as button clicks, mouse movement or clicks and keystrokes. Each of these events is represented in Java by a class that extends the AWTEvent class. The package java.awt.event contains the classes that support the Java event model, and must be imported into classes using event classes.
* Event Source – the particular GUI component with which the user interacts.
* Event Object – encapsulates information about the event that occurred, such as a reference to the event source (i.e. which button was clicked) and any event specific information that may be required by the event listener for it to handle the event.
* Event Listener – an object that is notified by the event source (i.e. button) when an event occurs. I.e. it listens for an event and one of its methods executes in response to the event. A method of the event listener receives an event object when the event listener is notified of the event.
4. Internationalization: - Java Internationalization (i18n) is Java's built-in support for making your app able to serve users in multiple different languages. In fact, internationalization covers more than just the language. It also covers formatting of numbers, adjustment to date and time etc.
Internationalization is what you do to a Java application to make it able to handle different languages, number formats etc.
Localization is what the Java application does when it adapts itself to a user with a specific language, number format, date and time etc.
Internationalization and localization are thus two sides of the same story. Your Java application needs to be internationalized to in order to be able to localize itself.
Internationalization is often abbreviated i18n. The 18 refers to the 18 characters between the first letter i, and the last letter n. Localization is similarly abbreviated as L10n.
5. Data Structure Classes:- Data Structure Classes are very useful classes for implementing standard computer science data structures: including BitSet, Dictionary, Hashtable, Stack and Vector. The Enumeration interface of java.util package is used to count through a set of values.
6. Date and time facilities: - The Date class is used to manipulate calendar dates in a system-independent fashion.
7. StringTokenizer: - This StringTokenizer class is used to convert a String of text into its tokens.
8. Properties: - The properties table contains key/value pairs where both the key and the value are Strings and the class is used by the System class to implement System properties.
9. Observer and Observable: - Classes that implement the Observer interface can "watch" Observable objects for state changes. When an Observable object changes it notifies all of its Observers of the change.
10. Random-Number Generator: - The Random Number Generator class is used to generate the random-numbers.
11. Enumeration: - The Enumeration interface defines a generic programming interface for iterating through a set of values.


Free Web Hosting