Recall that unlike some object-oriented languages, primitive data types are not objects in Java. However, there may be occasions when we need the object equivalents of primitive data types, as we have seen with Vectors. Java provides wrapper classes for this purpose. For example, we cannot directly convert a String, which is an object, into an int primitive; we need to do this directly or indirectly through the int object wrapper Integer. The wrapper classes for equivalent primitive data types are listed in Table 4.1.
Suppose we want to create an Integer object. We can do this like any object using the new keyword, as follows:
Integer intObj = new Integer(7);
To convert a String to an Integer, use the java.lang.Integer.valueOf method, for example
String snum = "456";
Integer intObj = Integer.valueOf(snum);
To convert an Integer object to an int primitive, we can use the
java.lang.Integer.intValue method,
for example
int count = intObj.intValue();
To convert a String to an int primitive, we can perform the previous two statements in one step using the java.lang.Integer.parseInt method, for example
int count = Integer.parseInt(snum);
4.11 Object Wrappers in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment