Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Java Wrapper Classes in Java

Java Wrapper Classes in Java

Wrapper Classes in Java

In Java, wrapper classes are used to convert primitive data types (such as int, char, double) into objects. Each primitive type has a corresponding wrapper class in the java.lang package. These wrapper classes are useful when you need to work with primitives in contexts where objects are required (e.g., in collections such as ArrayList).

List of Wrapper Classes

Here’s a table showing the primitive types and their corresponding wrapper classes:

Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
shortShort
intInteger
longLong
floatFloat
doubleDouble

Why Use Wrapper Classes?

  1. Object-Oriented Features: Sometimes, primitive types need to be treated as objects (for example, when working with Java collections).

  2. Autoboxing and Unboxing: Java automatically converts between primitive types and their wrapper objects. This is called autoboxing (from primitive to object) and unboxing (from object to primitive).

  3. Utility Methods: Wrapper classes provide utility methods for converting strings to primitives, comparing values, and more.


Autoboxing and Unboxing

  • Autoboxing: The automatic conversion of a primitive type to its corresponding wrapper class.

  • Unboxing: The automatic conversion of a wrapper class object to its corresponding primitive type.

Example: Autoboxing and Unboxing

public class WrapperExample {    public static void main(String[] args) {        // Autoboxing: converting int to Integer        int num = 10;        Integer numObj = num;  // automatically converted to Integer        // Unboxing: converting Integer to int        int num2 = numObj;  // automatically converted to int        // Display results        System.out.println("Primitive value: " + num);        System.out.println("Wrapper object: " + numObj);        System.out.println("Unboxed value: " + num2);    }}

Output:

Primitive value: 10Wrapper object: 10Unboxed value: 10

Wrapper Class Methods

Wrapper classes provide several useful methods, such as:

1. Parsing Strings to Primitive Values

You can convert a string to a corresponding primitive type using the parseXXX() methods.

String str = "123";int num = Integer.parseInt(str);  // Converts string to intSystem.out.println("Parsed Integer: " + num);String str2 = "3.14";double pi = Double.parseDouble(str2);  // Converts string to doubleSystem.out.println("Parsed Double: " + pi);

2. Getting the Type of a Value

Each wrapper class has a TYPE constant that holds the Class object for the corresponding primitive type.

Class<Integer> integerClass = Integer.TYPE;System.out.println("Integer TYPE: " + integerClass);

3. Comparing Values

Wrapper classes like Integer, Double, etc., provide compareTo() method to compare values.

Integer num1 = 100;Integer num2 = 200;int comparisonResult = num1.compareTo(num2);  // Returns negative value if num1 < num2System.out.println("Comparison result: " + comparisonResult);

4. Checking for null

Wrapper classes can be null, while primitive types cannot. This is useful for distinguishing between "no value" and a default value (like 0 for int).

Integer num3 = null;if (num3 == null) {    System.out.println("num3 is null");}

Example: Using Wrapper Classes in Collections

Since collections like ArrayList can only store objects, primitive types need to be wrapped in their respective wrapper classes.

import java.util.ArrayList;public class WrapperInCollection {    public static void main(String[] args) {        // Create an ArrayList to store Integer objects        ArrayList<Integer> numbers = new ArrayList<>();        // Adding primitive integers (autoboxing happens here)        numbers.add(10);  // Autoboxing from int to Integer        numbers.add(20);  // Autoboxing from int to Integer        numbers.add(30);  // Autoboxing from int to Integer        // Iterating over the list        for (Integer num : numbers) {            System.out.println("Number: " + num);        }    }}

Output:

Number: 10Number: 20Number: 30

Wrapper Class Constructors

Wrapper classes do not provide constructors for primitive types anymore (since Java 9). However, they do provide constructors to wrap String values.

Integer obj = new Integer("100");  // Deprecated in Java 9 and later

It’s recommended to use static methods like Integer.valueOf("100") instead.


Nullability of Wrapper Classes

Unlike primitive types, wrapper classes can be null, which is particularly useful when you need to indicate the absence of a value.

Integer a = null; // a is null

This behavior can be useful for certain scenarios, such as database records where a null value may indicate the absence of data.


Summary of Wrapper Class Methods

  • parseXXX(String str): Converts a string to the corresponding primitive type.

  • valueOf(String str): Returns a wrapper object for a string.

  • compareTo(): Compares the wrapper object with another.

  • toString(): Returns the string representation of the wrapper object.


Common Use Cases for Wrapper Classes

  1. Storing Primitives in Collections: Since Java collections like ArrayList, HashSet, and HashMap only store objects, wrapper classes are used to store primitive types.

  2. Nullability: Wrapper classes allow null values, which can be used to represent the absence of data.

  3. Utility Methods: Wrapper classes provide methods like parseInt(), valueOf(), and toString(), which are useful for type conversions and handling primitive values as objects.


Let me know if you'd like to see more examples or dive deeper into any part of wrapper classes in Java!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql