Java provides wrapper classes to convert primitive data types into objects. These classes are part of the java.lang package and offer various utility methods for type conversion, data manipulation, and object-oriented programming.
Wrapper classes in Java are used to encapsulate primitive data types within objects. Each primitive type has a corresponding wrapper class:
Primitive Type | Wrapper Class |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Before Java 9, wrapper classes had constructors to convert primitives into objects:
Integer obj = new Integer(10); // Deprecated
Instead of constructors, Java recommends using valueOf() for object creation:
Integer obj = Integer.valueOf(10);
Wrapper classes provide several utility methods for type conversion and manipulation.
Method | Description |
---|---|
parseInt(String s) | Converts a string to an int |
valueOf(String s) | Converts a string to an object |
toString() | Converts an object to a string |
doubleValue() | Returns the double equivalent |
intValue() | Returns the integer equivalent |
compareTo(T obj) | Compares two objects |
Example:
String number = "100"; int result = Integer.parseInt(number); System.out.println(result); // Output: 100
Autoboxing is the automatic conversion of a primitive type into its corresponding wrapper class.
int num = 50; Integer obj = num; // Autoboxing
Unboxing is the reverse process, where an object is converted back to a primitive type.
Integer obj = 100; int num = obj; // Unboxing
Copyrights © 2024 letsupdateskills All rights reserved