![]() |
VOOZH | about |
In Java, wrapper classes allow primitive data types to be represented as objects. This enables primitives to be used in object-oriented features such as collections, generics, and APIs that require objects.
Example: Converting Primitive to Wrapper (Autoboxing)
The primitive int b is: 357 The Integer object a is: 357
Explanation: Here, the primitive int value is automatically converted into an Integer object by Java. This automatic conversion is called autoboxing.
Wrapper classes are required in Java for the following reasons:
The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example: conversion of int to Integer, long to Long, double to Double, etc.
Java program to demonstrate the automatic conversion of primitive to wrapper class (Autoboxing).
25
Unboxing is the automatic conversion of a wrapper class object back into its corresponding primitive type.
24
Output:
| Primitive Data Type | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
| Method | Description | Example |
|---|---|---|
| parseXxx(String s) | Converts a String into its corresponding primitive type | int a = Integer.parseInt("100"); |
| valueOf(String s) | Converts a String into a wrapper object | Integer a = Integer.valueOf("100"); |
| valueOf(primitive) | Converts a primitive value into a wrapper object | Integer a = Integer.valueOf(10); |
| xxxValue() | Converts a wrapper object into its primitive type | int a = obj.intValue(); |
| toString() | Converts wrapper object into a String | String s = Integer.toString(10); |
| compareTo(Xxx obj) | Compares two wrapper objects | a.compareTo(b); |
| equals(Object obj) | Compares values, not references | a.equals(b); |
| hashCode() | Returns hash code of the object | obj.hashCode(); |
| min(x, y) | Returns minimum of two values | Integer.min(10, 20); |
| max(x, y) | Returns maximum of two values | Integer.max(10, 20); |
| sum(x, y) | Returns sum of two values | Integer.sum(10, 20); |
| compare(x, y) | Compares two primitive values | Integer.compare(10, 20); |
| isNaN() | Checks if value is Not a Number (Float/Double only) | Double.isNaN(val); |
| isInfinite() | Checks infinite value (Float/Double only) | Double.isInfinite(val); |
| decode(String s) | Decodes decimal, hex, or octal string | Integer.decode("0xA"); |
| parseBoolean(String s) | Converts string to boolean | Boolean.parseBoolean("true"); |