Learn the fundamental concepts of Arrays and Wrapper Classes in Java with examples, use cases, and best practices.
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.
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);
}
}
}
Arrays allow storing multiple values efficiently and access them using index numbers. They are useful for iteration, sorting, and storing fixed-size data.
Arrays have fixed size, can only store homogeneous data, and may waste memory if not fully utilized.
Wrapper Classes in Java provide an object representation of primitive data types. They allow primitive types to be treated as objects.
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);
}
}
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.
Use arrays for fixed-size data, collections for dynamic data, and wrapper classes when working with generics or needing object representation of primitives.