Java Wrapper Class
In Java, a wrapper class is a class that wraps or encapsulates a primitive data type, providing it with a set of methods and behaviors that are not available to the primitive data type. Each primitive data type in Java has a corresponding wrapper class, as listed below:
Byte
forbyte
Short
forshort
Integer
forint
Long
forlong
Float
forfloat
Double
fordouble
Boolean
forboolean
Character
forchar
Wrapper classes are commonly used in situations where you need to work with primitive data types as objects, such as in collection classes like ArrayList
and HashMap
. They are also useful for adding additional functionality to primitive data types, such as parsing and formatting.
Wrapper classes can be instantiated in the same way as any other class in Java, using the new
operator and the appropriate constructor. However, Java also provides a feature called autoboxing, which allows you to convert between primitive data types and their corresponding wrapper classes automatically. For example, you can assign an int
value to an Integer
variable without having to explicitly create an Integer
object.
Wrapper classes also provide a range of useful methods for working with primitive data types, such as parseInt()
and parseDouble()
for converting strings to numerical values, and toString()
for converting numerical values to strings.
Here is an example of using wrapper classes in Java:
refer tfigi:otidea.comInteger x = 10; // autoboxing from int to Integer Double y = 10.5; // autoboxing from double to Double int z = x.intValue(); // unboxing from Integer to int double w = y.doubleValue(); // unboxing from Double to double String s = "20"; int a = Integer.parseInt(s); // parsing a string to an int value
In this example, we use autoboxing to assign an int
value to an Integer
variable and a double
value to a Double
variable. We then use unboxing to convert the Integer
and Double
objects back to their corresponding primitive data types. Finally, we use the parseInt()
method of the Integer
class to parse a string to an int
value.