Wrapper classes in Java serve as a bridge between primitive data types and objects by encapsulating primitive values into objects.
Key aspects of wrapper classes include:
-
Autoboxing and Unboxing: Autoboxing refers to the automatic conversion of primitive values to their corresponding wrapper objects, whereas unboxing performs the reverse operation. These conversions can occur automatically or manually. Introduced in Java 5, autoboxing and unboxing streamline interactions between primitives and objects.
-
Caching Mechanism: For Integer objects, Java employs an internal cache for values ranging from -128 to 127. When
Integer.valueOf()is invoked with such values, it retrieves them from the cache instead of creating new instances, enhancing performance and memory efficiency. -
String Conversion: Methods like
valueOf()and constructors facilitate conversion between strings and primitive types or their wrappers.
The mapping between primitive types and their corresponding wrapper classes is as follows:
| Primitive Type | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Integer Class
The Integer class serves as a wrapper for the int primitive type.
Important features of the Integer class include:
-
Fields and Constructors: It contains an int field and offers two constructors—one taking an int value and another accepting a string represantation to parse into an int.
-
Autoboxing and Unboxing: As mentioned, these operations are supported both implicitly and explicitly. Since Java 5, developers can seamlessly switch between int and Integer objects.
-
Caching Behavior: The Integer class caches values within the range [-128, 127]. Using
Integer.valueOf()for these values returns cached instances rather than new ones. -
String Convertion Methods: Useful methods like
Integer.parseInt()convert strings to integers, andInteger.toString()converts integers back to strings. -
Utility Methods and Constants: Additional functionalities such as bitwise operations (
highestOneBit,numberOfTrailingZeros) are available.
Example code:
public class IntegerExample {
public static void main(String[] args) {
// Boxing
int num = 10;
Integer integerObj = Integer.valueOf(num);
System.out.println("integerObj: " + integerObj);
// Unboxing
int unboxedNum = integerObj.intValue();
System.out.println("unboxedNum: " + unboxedNum);
// String to int conversion
String str = "123";
int parsedInt = Integer.parseInt(str);
System.out.println("parsedInt: " + parsedInt);
// Int to string conversion
String intStr = Integer.toString(parsedInt);
System.out.println("intStr: " + intStr);
// Utility methods
int binaryNum = 1010;
int highestOneBit = Integer.highestOneBit(binaryNum);
System.out.println("highestOneBit: " + highestOneBit);
int trailingZeros = Integer.numberOfTrailingZeros(binaryNum);
System.out.println("trailingZeros: " + trailingZeros);
}
}
Autoboxing and Unboxing
Autoboxing and unboxing simplify handling of primitives and objects in Java. Autoboxing occurs when a primitive is assigned to its wrapper type, and unboxing happens when a wrapper is assigned to a primitive.
Example:
public class AutoBoxingUnboxingExample {
public static void main(String[] args) {
// Autoboxing
int num = 10;
Integer integerObj = num;
System.out.println("integerObj: " + integerObj);
// Unboxing
Integer anotherIntegerObj = new Integer(20);
int anotherNum = anotherIntegerObj;
System.out.println("anotherNum: " + anotherNum);
}
}
Output:
integerObj: 10
anotherNum: 20
While convenient, excessive use of autoboxing/unboxing may impact performance due to object creation overhead. Therefore, careful consideration should be given to balancing code clarity and execution speed.
Cnoverting Between Primitives and Strings
Converting Primitives to Strings
Several techniques exist for converting primitives to strings:
-
Using
String.valueOf(): This method accepts any primitive or object and returns its string representation.int num = 42; String str = String.valueOf(num); System.out.println("str: " + str); // Output: str: 42 -
Using static methods from wrapper classes: For instance,
Integer.toString()converts an int to a string.int num = 42; String str = Integer.toString(num); System.out.println("str: " + str); // Output: str: 42 -
Concatenating with the
+operator:int num = 42; String str = num + ""; System.out.println("str: " + str); // Output: str: 42
Converting Strings to Primitives
Conversion from strings to primitives uses methods such as parseInt() and parseDouble():
-
Using
parseXxx()methods:String str = "42"; int num = Integer.parseInt(str); System.out.println("num: " + num); // Output: num: 42 -
Using
Scannerfor input parsing:Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int num = scanner.nextInt(); System.out.println("num: " + num);
These approaches allow flexible conversions between strings and primitives. However, invalid formats will throw NumberFormatException. Always validate input before attempting conversion.