Primitive Data Types and the Wrapper Classes
Java provides the classes Integer, Double, Character, Long, and Float so that values of primitive data types can be treated as objects. These classes are calledwrappers. They wrap primitive type values. However, these classes have limitations that have to be followed. You can create objects of the type, Integer, to store int values, but you cannot change the value stored in the objects. Parameter passing is a fundamental concept in any programming language. Therefore, we have created the classes IntClass and DoubleClass, which are similar to the classes Integer and Double, respectively. You can create objects of the type IntClass and/or DoubleClass, store, and/or change values of the objects.
The data members and methods in this class are:
data member: int x;
public IntClass()
public IntClass(int num)
public void setNum(int num)
public int getNum()
public void addToNum(int num)
public void multiplyToNum(int num)
public int compareTo(int num)
public Boolean equals(int num)
public String toString()
As of J2SE 5.0, Java has simplified the wrapping and unwrapping of primitive type values, called the autoboxing and auto-unboxing of primitive types. An example of autoboxing is as follows:
int x;
Integer num;
num = 25;
The third statement is equivalent to the statement
Num = new Integer( 25 );
This is an example of autoboxing.
An example of auto-unboxing is:
x = num;
This is equivalent to the statement
x = num.intValue();
Teaching Tip
|
More information on autoboxing can be found at:
|
Teaching Tip
|
A listing of all of the wrapper classes in the java.lang package can be found at:
|
No comments:
Post a Comment