BhauAutomation

Arrays & Wrapper Classes in Java

Learn the fundamental concepts of Arrays and Wrapper Classes in Java with examples, use cases, and best practices.

What are Arrays in Java?

An Array in Java is a collection of elements of the same type stored in contiguous memory locations. Arrays are used to store multiple values in a single variable.

Example of Arrays

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        System.out.println("Array Elements:");
        for(int num : numbers) {
            System.out.println(num);
        }
    }
}
  

Advantages of Arrays

Arrays allow storing multiple values efficiently and access them using index numbers. They are useful for iteration, sorting, and storing fixed-size data.

Limitations of Arrays

Arrays have fixed size, can only store homogeneous data, and may waste memory if not fully utilized.

What are Wrapper Classes in Java?

Wrapper Classes in Java provide an object representation of primitive data types. They allow primitive types to be treated as objects.

Example of Wrapper Classes

public class WrapperExample {
    public static void main(String[] args) {
        int num = 50;
        Integer wrapperNum = Integer.valueOf(num); // Boxing
        int unboxedNum = wrapperNum.intValue(); // Unboxing
        System.out.println("Original Number: " + num);
        System.out.println("Wrapper Number: " + wrapperNum);
        System.out.println("Unboxed Number: " + unboxedNum);
    }
}
  

Purpose and Advantages

Wrapper classes allow primitives to be used in Java Collections (like ArrayList, HashMap) and provide methods for data conversion, comparison, and utility functions. They also support Autoboxing and Unboxing.

Best Practices

Use arrays for fixed-size data, collections for dynamic data, and wrapper classes when working with generics or needing object representation of primitives.