Page Content

Tutorials

How many types are in an Array in Java? Explained With Code

Array in Java

A basic data structure in Java, arrays are container objects that can store a set number of values of a single type. This requirements that every element in an array be of the same data type, including characters, numbers, or even other objects. Java uses objects instead of raw data types to implement arrays, in contrast to several other computer languages. Automatic garbage collection for unused arrays is one of the many benefits of this object-oriented approach.

Declaring and Initialising One-Dimensional Arrays

In Java, you must first declare a variable to reference the array and define the kind of elements it will contain before you can use it. DataType[] arrayRefVar; is the recommended syntax for declaring an array variable. Although it is also possible, it is typically not advised to use dataType arrayRefVar[]; since the array type should be indicated by the brackets. Although the array is not really created in memory by this declaration, it does notify the compiler that the variable will contain an array of the designated type.

Two methods exist for initialising arrays:

  1. Using the new operator: This method allocates memory for the array and sets its length. The general form is arrayRefVar = new dataType[arraySize]; or combined with declaration: dataType[] arrayRefVar = new dataType[arraySize];. When an array is created with new, its elements are automatically initialised to default values: 0 for numeric types, '\u0000' (null character) for char, false for boolean, and null for reference types. The size of an array is fixed at runtime once created.
  2. Using shortcut syntax (array initializer): Another method for declaring and initialising an array is to use shortcut syntax (array initialiser), in which the length of the array is defined by the number of items enclosed in braces. Use of this form is limited to the moment of declaration.

Accessing Array Elements (Indexing)

An array’s items are referred to as elements, and each element can be retrieved by its integer index. The array indexing in Java is zero-based, which means that up to length -1, the first member is at index 0, the second at index 1, and so on. If an element is accessed outside of this acceptable range (for example, if the index is negative or higher than or equal to the length of the array), an ArrayIndexOutOfBoundsException will be raised.

Here’s a comprehensive code example demonstrating declaration, initialisation, and access of one-dimensional array elements:

class ArrayDemo {
    public static void main(String[] args) {
        // Declares an array of integers
        int[] anArray; 
        // Allocates memory for 10 integers
        anArray = new int; 
        // Initialize first element
        anArray = 100;
        // Initialize second element
        anArray = 200; 
        // and so forth
        anArray = 300; 
        anArray = 400; 
        anArray = 500; 
        anArray = 600; 
        anArray = 700; 
        anArray = 800; 
        anArray = 900; 
        anArray = 1000;
        System.out.println("Element at index 0: " + anArray); 
        System.out.println("Element at index 1: " + anArray); 
        System.out.println("Element at index 2: " + anArray); 
        // ... (output for other elements would follow similarly)
    }
}

Output:

Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000

The Property

Because they are objects, arrays have an instance variable called length that tells you how many elements the array can hold. This attribute indicates the array’s capacity rather than the quantity of components that are presently being used. When handling array elements, the length attribute is incredibly helpful in managing loops.

System.out.println(anArray.length); 

Output (for the anArray above):

10

Multidimensional Arrays

Multidimensional arrays in Java are basically arrays of arrays. An array with each element being a one-dimensional array is called a two-dimensional array, for instance.

Declaration and Initialisation: Using two or more sets of brackets to declare a multidimensional array is known as declaration and initialisation. The general form for a two-dimensional array declaration and initialisation is: type[][] arrayName = new type[rows][columns]; Or, you can initialise it directly: type[][] array_name = { {val, val, ...}, {val, val, ...}, ... };

Additionally, Java allows for irregular (or ragged) arrays, in which the lengths of the rows in a multidimensional array can vary. This is due to the fact that arrays whose components are arrays themselves are used to implement multidimensional arrays.

Accessing Elements: Elements in a multidimensional array can be accessed by a corresponding number of index values, which are similar to names in a two-dimensional array.

Example of a two-dimensional array:

class MultiDimArrayDemo {
    public static void main(String[] args) {
        String[][] names = {
            {"Mr. ", "Mrs. ", "Ms. "},
            {"Smith", "Jones"}
        }; 
        // Mr. Smith
        System.out.println(names + names); 
        // Ms. Jones
        System.out.println(names + names); 
    }
}

Output:

Mr. Smith
Ms. Jones

Iteration using Enhanced For Loop: Originally introduced in Java 5, the enhanced for loop (also known as the for-each loop) allows you to iterate through arrays, including multidimensional ones. Every iteration over a multidimensional array yields the subsequent array (N-1 dimensions), not a single element. As a result, complete access usually uses nested loops.

class EnhancedForDemo {
    public static void main(String[] args){
        int[] numbers = {1,2,3,4,5,6,7,8,9,10}; 
        for (int item : numbers) { // item holds the current value from the array
            System.out.println("Count is: " + item);
        }
    }
}

Output:

Count is: 1
Count is: 2
...
Count is: 10

For multidimensional arrays, you would nest the enhanced for loops:

class ForEach2 {
    public static void main(String args[]) {
        int sum = 0;
        int nums[][] = new int;
        // give nums some values
        for(int i = 0; i < 3; i++)
            for(int j=0; j < 5; j++)
                nums[i][j] = (i+1)*(j+1);
        // Use for-each for loop to display and sum the values.
        for(int x[] : nums) { // x is a reference to a one-dimensional array
            for(int y : x) { // y is an individual element
                System.out.println("Value is: " + y);
                sum += y;
            }
        }
        System.out.println("Summation: " + sum);
    }
}

Output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
... (rest of the elements)
Summation: 90
Index