Flat Preloader Icon

Arrays, Boxing & Unboxing

Note: Arrays, boxing, and unboxing are important concepts in Java related to handling data, especially primitive data types and their object counterparts. Let’s explore these concepts

Arrays

  • Java object used to group primitives or objects.
  • All components have the same type, e.g. int, String etc.
  • Size cannot be changed after creation.
  • Some methods:-
    • public static int[] copyOf(int[] original, int newLength)
    • public static int[] copyOfRange(int[] original,int from, int to)

Declaration

  • You declare an array by specifying the data type, followed by square brackets [], and then the array name. For example, int[] numbers; declares an integer array.

Initialization

  • You can initialize an array when declaring it or separately using the new keyword. For example:
    • Declaration with initialization: int[] numbers = {1, 2, 3, 4, 5};
    • Separate initialization: int[] numbers = new int[5]; (creates an array of size 5)

    Boxing & Unboxing

    • Wrapper classes v/s primitive variables. .
    • Conversion of primitive type to Wrapper type is called boxing.
    • Conversion of Wrapper type to primitive type is called unboxing..

    Varargs

    • Pass any number of parameters in a method.
    • E.g. public int checksum(int … vals)
    • Helpful when one needs a flexibility of passing some unknown number of parameters, without creating an array.

    format & printf methods

    • Examples of using Varargs
    • E.g public static String format(String formatString, Object… args)