Java Array Explained [Easy Examples]

Related Searches: java initialize array, string array in java, java array size, java int array, how to create an array in java, java new array, how to make an array in java, integer array in java, java make array, java array example, java array of arrays, java instantiate array, java array syntax, string array declaration in java, integer array, java create new array, java declare int array, initialize int array java, new int, how to make an array java, new int java, create int array java, how to define array in java, how to use array in java 

 

Introduction to the Java array

An Array is one of the data structures in Java, which is a collection of variables of the same data type that are referenced by a common name. Arrays consist of contiguous memory locations. The first address of the array belongs to the first element and the last address to the last element of the array.

Advertisement

In this tutorial, we will learn about java array. We will learn how we can declare single and multidimensional arrays along with various examples. We will also cover how we can find the length of an array, arrays indexing, and iterating over an array to print the elements. At the same time, we will also discuss how we can insert elements into java array using different examples.

 

Getting started with Java array

Java Arrays are a collection of variables of the same type. For instance, an array of String is a collection of variables of the type String. The variables in the array are ordered and each has an index. The indexing starts from 0 and so on. The very first element will be at index 0 and the very last will be at the index of one less than the length of an array.  See the diagram below which shows an array with indexing.

Java array Explained [Easy Examples]

 

Declaring an array variable in Java

A Java array variable is declared just like we declare other variables of the desired type, except that here we add [] after the type. Here is a simple syntax of  array declaration in Java;

dataType [] ArrayName;

An array is simply a variation of the data type. Instead of being a single variable of that type, it is a collection of variables of that type. Now let us see how we can instantiate the declared array.

 

Instantiating Java array

When we declare array variables in java, actually we only declare the variables (reference) to the arrays. The declaration does not actually create an array. We need to create an array. See the syntax below:

ArrayName = new dataType[ArraySize];

This will now create an array of the specified size. The newly created array will be of primitive data type.

Advertisement

However, we can also create an array object as well. The following is the simple syntax of creating an array object in Java.

Datatype[] arrayName = new DataType[ArraySize];

This will create an object of type array.

 

Examples of different data typed Java array

Now we already know the basic syntax of the declaration of java array. Here we will create an array of different data types. There are a number of different ways to instantiate primitive data typed array, we will see some of the commonly used ones here.

See the following java code where we create array of different types.

// class
public class Main  { 
    public static void main(String[] args){
        // method  to create java array
        // declaring arrays
        String[] array1;
        int[] array2;
        char[] array3;
        // initializing arrays
        array1 = new String[3];
        array2 = new int[4];
        array3 = new char[4];
    }
}

Notice that the above method takes too many lines. However, in java, there is a more simple way to create arrays along with elements. See the example below;

// class
public class Main  { 
    public static void main(String[] args){
    // method 1 to create java array
    String[]   array1 = new String[]{"bashir", "alam", "UCA" };
    int[]  array2 = new int[]{1, 2, 3, 4, 5};
    char[] array3 = new char[]{'a', 'b', 'c'};
    }
}

Notice that the values that have been inserted into the array are listed inside the curly brackets. The length of this list also determines the length of the created array. This is a valid declaration and initialization of a array in Java. However, we can create it without using the new keyword. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
    // method to create java array
    String[] array1 = {"Bashir", "Alam", "UCA" };
    int[]  array2 =  {1, 2, 3, 4, 5};
    char[] array3 = {'a', 'b', 'c'};
    }
}

Notice that in the above couple of examples, we didn't explicitly mention the size of an array. In such cases we can easily find out the length of an array. In the following section, we will see how we can find the length of an array.

 

Finding the length of Java array

Now let us find the length of an array. We use the java length method to get the size of an array. See the example below which use the length method to find the size of array in Java.

Advertisement
// class
public class Main  { 
    public static void main(String[] args){
        //declaring arrays
        String[] array1 = {"Bashir" ,"Alam", "UCA"};
        int[] array2 = {1,2,3,4,5,6};
        char[] array3 = {'a','b','c','d'};
        
        // printing the lenght
        System.out.println("Size of array1 is :" + array1.length);
        System.out.println("Size of array2 is :" + array2.length);
        System.out.println("Size of array3 is :" + array3.length);
    }
}

Output:

Size of array1 is :3
Size of array2 is :6
Size of array3 is :4

Notice that we get the correct sizes of array length.

 

Printing Java array in different ways

There are multiple ways to print java array. In this section, we will discuss three ways to print java array.

 

Using Arrays.ToString() method to print Java array

Direct printing java array is not allowed. We will get unexpected output if we try to print java array directly. That is why we have to use Arrays.ToString() method to print the arrays as they are. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        //declare arrays
        String[] array1 = {"Bashir" ,"Alam", "UCA"};
        int[] array2 = {1,2,3,4,5,6};
        char[] array3 = {'a','b','c','d'};
        
        // printing the array
        System.out.println("array1 is :" + Arrays.ToString(array1));
        System.out.println("array2 is :" + Arrays.ToString(array2));
        System.out.println("array3 is :" + Arrays.ToString(array3));
    }
}

Output:

array1 is :[Bashir, Alam, UCA]
array2 is :[1, 2, 3, 4, 5, 6]
array3 is :[a, b, c, d]

Notice that we successfully print out the arrays using Arrays.ToString() method.

 

Print Java array through Indexing

Now suppose we don't want to print the whole array, in fact, we want to print some elements. We can do that by using the java indexing method. This method allows us to print individual elements of java array. We already know that the java indexing starts from 0, not from 1. See the example below which prints the individual elements using the java indexing method.


// class
public class Main  { 
    public static void main(String[] args){
        //declare array
        char[] array1 = {'a','b','c','d'};
        
        // printing the array elements
        System.out.println("Element at positon 0 is :" + array1[0]);
        System.out.println("Element at positon 2 is :" + array1[2]);
        System.out.println("Element at positon 3 is :" + array1[3]);
    }
}

Output:

Element at positon 0 is :a
Element at positon 2 is :c
Element at positon 3 is :d

Notice that it prints the elements at specified positions.

 

Iterating over an array

If we want to print all the elements of an array individually, then it is not a good idea to use indexing. We can iterate over java array to print out all the elements. See the example below, which uses java for loop to iterate and print out all the elements one by one.

// class
public class Main  { 
    public static void main(String[] args){
        //declare array
        char[] array1 = {'a','b','c','d'};
        
        // for loop
        for(int i=0; i<array1.length; i++){
            System.out.println(array1[i]);
        }
    }
}

Output:

a
b
c
d

Notice that in one go, we printed all the elements of an array individually using java for loop.

 

Multidimensional Java array

So, far we have been working with single-dimensional arrays. In this section, we will deal with multidimensional arrays. The Java multidimensional arrays are arranged as an array of arrays. For example, each element of a multi-dimensional array is another array. The representation of the elements is in rows and columns. Thus, we can get a total number of elements in a multidimensional array by multiplying row size with column size. Let us first learn how we can declare multidimensional arrays in java.

 

Declaring and initializing multidimensional Java array

We can create a multidimensional array in Java by appending one set of square brackets ([]) per dimension. Here is the simple syntax of the java multidimensional arrays declaration and initialization.

Datatype[][] arrayName = new int[columnSize][rowSize];

Now let us create a multidimensional array in Java. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // multidimensional java array
        char[][] array1 = {{'a', 'b', 'c'},{'e','f','g'}};  
    }
}

Now let us see how we can iterate over the multi-dimensional array.

 

Iterating over multidimensional Java array

When we iterate a multidimensional array in Java,  we need to iterate each dimension of the array separately. We use nested loops to iterate multidimensional java array. See the example below which iterates over a multidimensional array using nested java for loop.

// class
public class Main  { 
    public static void main(String[] args){
        // multidimensional java array
        char[][] array1 = {{'a', 'b', 'c'},{'e','f','g'}};  
        // iterating using for loop
        for(int i =0; i<2; i++){
            System.out.println("Elements of row "+ i);
            // inner for loop
            for (int k =0; k<3; k++){
                // printing elements
                System.out.println(array1[i][k]);
            }
        }
    }
}

Output:

Elements of row 0
a
b
c
Elements of row 1
e
f
g

 

Inserting elements into Java array

Sometimes we might don't want to insert values at the beginning of the program or we may want the user to add the elements one by one. The following is the simple syntax of inserting elements into java array;

ArrayName[Position] = element;

This will add new value to the specified position. Now let us take an example and add insert new elements into an array. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // declaring new array
        char[] array1 = new char[5];

        // inserting new elements
        array1[0]='a';
        array1[1]='b';
        array1[2]='c';
        array1[3]='d';
        array1[4]='e';

        // printing the array
        System.out.println(Arrays.toString(array1)); 
    }
}

Output:

[a, b, c, d, e]

Notice that we had successfully inserted elements to the specified positions in a java array.

 

Summary

An array in Java is a set of variables referenced by using a single variable name combined with an index number. Each item of an array is an element. All the elements in an array must be of the same type. For example, an int array can contain int values, and a String array can contain only strings. In this tutorial, we learned about java array.

We learned how we can declare single and multidimensional arrays in java using various examples. We also covered how we can print an array in java using different methods and iterating over it. Moreover, we also discussed how to insert elements into an array one by one. All in all, this tutorial contains all the basic information that you need to learn in order to start working with java array.

 

Further Reading

java array
java array documentation
More about java array

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment