If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, wrapper classes are used to convert primitive data types into objects, allowing them to be treated as objects. Each primitive data type has a corresponding wrapper class, and these classes are part of the java.lang
package, so you don't need to import them explicitly.
The following are the primitive data types and their corresponding wrapper classes:
byte
- Byte
short
- Short
int
- Integer
long
- Long
float
- Float
double
- Double
char
- Character
boolean
- Boolean
Wrapper classes are particularly useful in scenarios where you need to use objects instead of primitive data types. For example, when working with collections like ArrayList or when using Java generics, as generics don't support primitive data types.
Here are some examples of using wrapper classes:
javaCopy code
int age = 25;
Integer ageObj = age; // Autoboxing: converting int to Integer
javaCopy code
Double heightObj = 1.75;
double height = heightObj; // Unboxing: converting Double to double
javaCopy code
String numberStr = "123";
int number = Integer.parseInt(numberStr); // Converts string to int using Integer wrapper class
javaCopy code
double price = 19.99;
String priceStr = Double.toString(price); // Converts double to string using Double wrapper class
Wrapper classes also provide useful utility methods, such as converting strings to numbers, comparing values, etc. When using wrapper classes, be cautious of possible null values as they can cause NullPointerExceptions. In Java 8 and above, you can use Optional
to handle null values more safely.
Comments: 0