Академический Документы
Профессиональный Документы
Культура Документы
Wrapper Classes
1. Overview
Java provides an object wrapper for each of the eight primitive data types. These wrappers basically define an object container to store the primitive data type. In addition, the wrapper classes define constants for the data types (for example, MAX_VALUE, MIN_VALUE), and provide a suite of methods to convert between data types and perform operations. The wrapper classes belong to the java.lang package. Selected source code from the Integer wrapper class:
public final class Integer extends Number { public static final int MIN_VALUE = 0x80000000; public static final int MAX_VALUE = 0x7fffffff; private int value; public Integer( int value ) { this.value = value; } public static Integer valueOf( String s, int radix ) throws NumberFormatException { return new Integer(parseInt(s,radix)); } ... }
All the wrapper classes support the following constructors and methods: A constructor that accepts a primitive data type and creates an object of the type class. A constructor that accepts a single String parameter and creates an object with an initial value based on the decoded String. A data-typeValue method that returns the value of the object as the specified data-type. An equals() method to compare objects for equality. A hashCode() method to compute the has code value for the object. A toString() method that generates the string representation of the wrapper object.
Wrapper Classes
For integer data types use corresponding class method: parseByte, parseShort, parseInt, parseLong. For floating point data types use valueOf to create a wrapper object from a String input and then use corresponding data-typeValue method to covert the object to the desired primitive data type. String number = "-37"; int k1 = Integer.parseInt( number ); int k2 = Integer.parseInt( "2458" ); double d1 = Double.valueOf( "31.6" ).doubleValue(); double d2 = Double.valueOf( number ).doubleValue();
Convert String to Double object. Dot operator, . is left associative (left to right).
Wrapper Classes
public String toString() public static String toString( int num ) Generates a String representation of an int, or Integer object. public static Integer valueOf( String str ) throws NumberFormatException Creates an Integer object based on the decoded String. try { Integer k = Integer.valueOf( 1998 ); } catch ( NumberFormatException e) { System.out.println( Could not convert string to integer. ); }