Wrapper Classes: A Few Additions in J2SE 5.0 (Part-1)

The type wrapper classes were provided in Java libraries since its first release. J2SE 5.0 made several useful additions to its methods. For example, the Integer class now provides methods for bit manipulations. 

rotateRight and rotateLeft Methods

•The rotateRight method rotates the represented number to the right. The rotation is performed on the Two’s Complement binary representation of the number. Thus, the rightmost bit that is rotated out re-enters on the left side. 

•Similarly, the rotateLeft method rotates the represented number to the left. The bit shifted out re-enters on the right side. 

•A rotateRight operation by one digit results in arithmetic division by two, and a rotateLeft operation results in multiplication by two. 

The following code snippet illustrates the use of these methods:

Integer n1 = new Integer(0x100);

Integer n2 = new Integer(0x1);

n1 = Integer.rotateRight(n1, 1);

n2 = Integer.rotateLeft(n2, 1);

The second parameter to the rotate operation specifies the number of bits by which the rotation is to be performed. If we rotate the number by 32, its value remains unaffected.

Other Methods

•J2SE 5.0 also introduced a few bit-manipulation methods: The bitCount method returns The number of 1’s in the Two’s Complement binary representation of its input argument;

•The numberOfLeadingZeros and numberOfTrailingZeros methods return the count of leading and trailing zeros, respectively, as indicated by their names. 

•The toBinaryString method returns a string containing the binary representation of the specified number. This representation does not print the leading zeros. 

•Likewise, the toHexString and toOctalString methods return the hexadecimal and octal representations. We could also use the toString method to obtain a string representation of a number to any arbitrary radix. 

For example, the following code fragment prints the string “3333” to the console:

•Integer n = new Integer(255);

•System.out.println("Radix4: " + Integer.toString(n, 4));

Additional Functionality

The functionality of the wrapper classes mentioned so far applies to most of the wrapper classes in this category. A few wrapper classes provide additional functionality, as detailed in this section.

The Double class that wraps a double data type contains three fields: 

•NaN (Not-a-Number)



It also provides the:

•isNaN method

•isInfinite method

 to test for NaN and Infinity conditions. For example, the following two statements print true to the console in each case:

•System.out.println(Double.isNaN(new Double(0 / 0.0)));

•System.out.println(Double.isInfinite(new Double(1 / 0.0)));

If we attempt 0/0 or 1/0, it is treated as integer division and results in a divide-by-zero ArithmeticException. This is the reason behind using 0.0 in the preceding expressions, which is a double number by its default representation.

  Modified On Mar-31-2019 11:26:42 AM

Leave Comment