Previous
Index

Next


Objective 3, The wrapper classes

Describe the significance of wrapper classes, including making appropriate selections in the wrapper classes to suit specified behaviour requirements, stating the result of executing a fragment of code that includes an instance of one of the wrapper classes..DoubleValue, floatValue, longValue,parseXxx,getXxx,toString,toHexString.

Comment on this objective.

This topic was only added in explicitly with the release of the JDK1.4 version of the exam, so if you look at mock exams for earlier versions it may not contain questions on this topic. In real world programming you will frequently make use of the wrapper classes so this should be a relatively easy topic to learn. Take particular care to learn the methods mentioned on the objective as you can be confident that they are mentioned in questions on the real exam question database.

What are wrappers

Rappers are performers or heavily rhymed couplets backed by a beat heavy rhythm in the popular music genre. However in Java wrappers are classes that wrap up primitive values in classes that offer utility methods to manipulate the values. If for example you want to store a set of int values in the elements of a Vector, the values in a Vector must be objects and not primitives. When you want to retrieve the values wrapped up in the Integers that are in the Vector elements you will need to cast the elements back to Integers and then call the toxxValue in order to get back the original number. The following code demonstrates this technique.

import java.util.*;
public class VecNum{
    public static void main(String argv[]){
    Vector v = new Vector();
    v.add(new Integer(1));
    v.add(new Integer(2));
    for(int i=0; i < v.size();i ++){
        Integer iw =(Integer) v.get(i);
        System.out.println(iw.intValue());
    }
   }
}



The wrapper classes also offer utility methods for converting to and from the int values they represent. Thus if you have a string that could also represent a number, you can use a wrapper class to perform that calculation.

The methods of the wrapper classes are all static so you can use them without creating an instance of the matching wrapper class. Note that once a wrapper has a value assigned to it that value cannot be changed.



Once assigned a value, the value of a wrapper class cannot be changed



If you get questions on the exam that involve methods like Integer.setInt(int i) you can be confident it is a bogus code that is incorrect.

Utility methods

One of the most useful type of wrapper utility methods are the parseXX methods that turn a String that can represent a number into the primitive version of that number. The use of XX is to stand in for any of the data types that the wrappers can contain, thus it includes parseInt, parseLong, parseShort, parseCharacter, parseBoolean If you have a web page with a form field that should represent a number, the value that will be returned will be a String that might be convertible into a number. Thus the field might contain “101” or “elephant”. You can use the wrapper classes to attempt to convert the string into the desired primitive type. If it cannot be converted appropriately (ie if it contained “elephant”) then a NumberFormatException will be thrown.

Here is an example of some code that takes in a String from the command line and if it can represent an int will convert to an int, if not it will show an error message.

     

The wrapper classes can take constructors of either the type they are designed to wrap or of a String that can be converted to that type. Thus the Integer class can take a number that could be contained by an int, but an error will occur if you try to pass a number with a floating point component. Remember that the wrapper classes are just that classes, they are not primitives and instances of the wrappers can only be manipulated in the same way as any class. You may get questions on the exam with code that uses standard math operations to manipulate instances of wrappers. You can of course use the + operator where it would implicitly call the toString method, but as soon as you see the - * or % operator, beware.

public class String2Int{
    public static void main(String argv[]){     
    try{
        int i= Integer.parseInt(argv[0]);
        System.out.println("Coverted to int val = " + i);
        }catch(NumberFormatException nfe){                  System.out.println("Could not covert to int");
        }   
    }
}

       

toHexString

The toHexString method does approximately what you expect in that it returns a string which is a hex string version of the number. It has a natural partner in the toBinaryString method which returns a string that represents the number in its binary version. To understand what these methods are likely to return you need to have a basic understanding of binary and hex number representation. You will need to understand those concept for the objectives relating to bit shifting. The following example code will output the strings 100 followed by 10.

public class NumberFormats{
    public static void main(String argv[]){
    System.out.println(Integer.toBinaryString(4));
    System.out.println(Integer.toHexString(16));

    }
}
    
   

Questions

Question 1)

Which of the following statements are true?

1) The Integer class has a String and an int constructor
2) The Integer has a floatValue() method
3) The wrapper classes are contained in the java.lang.Math package
4) The Double class has constructors for type double and float



Question 2)

What will happen when you attempt to compile and run the following code?

public class WrapMat{
    public static void main(String argv[]){
    Integer iw = new Integer(2);
    Integer iw2 = new Integer(2);
    System.out.println(iw * iw2);
    System.out.println(iw.floatValue());
   }
}



1 )Compile time error
2) Compilation and output of 4 followed by 2.0
3) Compilation and output of 4 followed by 2
4) Compile time error, the Integer class has no floatValue method

Question 3

What will happen when you attempt to compile nad run the following code?

public class TwoEms {
    public static void main(String argv[]){
        Object[] oa = new Object[3];
        oa[0] = new Integer(1);
        int i = oa[0];
        System.out.print(i);
        
    }
    
}

1) Compile time error an array cannot contain object references
2) Compile time error elements in an array cannot be anonymous
3) Compilation and output of 1
4) Compile time error Integer cannot be assigned to int
5) Compilation and output of the memory address of the Integer instance

       

Question 4)

What will happen when you attempt to compile and run the following code?

public class TwoPack {
    public static void main(String argv[]){
        Integer iw = new Integer(“2”);
        Integer iw2 = new Integer(“2”);
        String sOut = iw + iw2;
        System.out.println(sOut);
        
    }
    
}



1) Compile time error, the + operator cannot be applied to Integer
2) Compilation and output of 22
3) Compilation and output of 4
4) Compile time error, Integer has no String constructor

Question 5)

Which of the following is valid code?

1) System.out.println(Integer.toBinaryString(4));
2) System.out.println(Integer.toOctalString(4));
3) System.out.println(Integer.add(2,2));
4) Float[] ar = new Float[] { new Float(1.0), new Float(2.1)};



Answers

Answer to Question 1

1) The Integer class has a String and an int constructor
2) The Integer has a floatValue() method
4) The Double class has constructors for type double and float

Answer to Question 2

1 )Compile time error

Instances of wrapper classes cannot be manipulated like primitives. Note that the Integer class does actually have a floatValue method.

Answer to Question 3

4) Compile time error Integer cannot be assigned to int

This code could be made to work by using the intValue method of the Integer class. As it is an instance of a class cannot be assigned to a primitive variable.

Answer to Question 4

1) Compile time error, the + operator cannot be applied to Integer

Instances of the wrapper classes cannot be manipulated as if they were primitives. They are instances of classes and you need to extract the primitive values in order to perform maths on the values represented.

Answer to Question 5

1) System.out.println(Integer.toBinaryString(4));
2) System.out.println(Integer.toOctalString(4));
4) Float[] ar = new Float[] { new Float(1.0), new Float(2.1)};

The wrapper classes contain no methods for manipulating the contents as if they were primitives, thus add method in option 3 does not exist. If you want to do that you need to extract the primitive values represented and work on them.

Other sources on this topic

This topic is covered in the Sun Tutorial at
http://java.sun.com/docs/books/tutorial/essential/strings/stringsAndJavac.html
(doesn't go into much detail)

Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec9.html#obj29






Previous
Index

Next