Java Array Tutorial for Beginners

This tutorial has designed for Java beginners to quickly learn about Arrays in Java with examples.

An Array is a container object that holds a fixed number of values of a single type. As we know Array is a data structure where we store similar elements and Array starts from index 0. The length of an array is established when the array is created. After creation, its length is fixed.


Table of contents

  1. Overview of an Array
  2. Array Types
  3. Declare an Array Example
  4. Create an Array Example
  5. Initializing an Array Examples
  6. Accessing an Array Examples
  7. Shortcut Syntax to Create and Initialize an Array
  8. Java Array Copy Examples(Four Ways)
  9. Java Print Array Content Example
  10. Advantage of Java Array
  11. Limitation of an Array

1. Overview of an Array

  • An array is a container object that holds a fixed number of values of a single type.
  • The length of an array is established when the array is created. After creation, its length is fixed.
  • Each item in an array is called an element, and each element is accessed by its numerical index.
  • Since arrays are objects in Java, we can find their length using member length.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each has an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an int value and not long or short.

2. Array Types


There are two types of array.
  1. Single Dimensional Array
  2. Multidimensional Array

1. Single Dimensional Array with Example

An array which stores only primitives or objects is called a single-dimensional array. For example, let's creates an array of integers, puts some values in the array, and prints each value to standard output.
public class ArrayBasics {
        public static void main(String[] args) {
        // declares an array of integers
        int[] anArray;
 
        // allocates memory for 10 integers
        anArray = new int[10];
            
        // initialize first element
        anArray[0] = 100;
        // initialize second element
        anArray[1] = 200;
        // and so forth
        anArray[2] = 300;
        anArray[3] = 400;
        anArray[4] = 500;
        anArray[5] = 600;
        anArray[6] = 700;
        anArray[7] = 800;
        anArray[8] = 900;
        anArray[9] = 1000;
 
        for (int i = 0; i < anArray.length; i++) {
                System.out.println("Element at index " + i + ": " +anArray[i]);
        }
}
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

2. Two Dimensional Array with Example

A multi-dimensional array stores other arrays. It is an array of arrays. In multi-dimensional array, each element of the array holding the reference of other arrays. A multidimensional array is created by appending one set of square brackets ([ ]) per dimension.

class MultiDimArrayDemo {
                                                                                 
    public static void main(String[] args){
        String[][] names = {
            {"Mr. ","Mrs. ","Ms. "},
            {"Smith","Jones"}};
 
        // Mr. Smith
        System.out.println(names[0][0] +
                           names[1][0]);
        // Ms. Jones
        System.out.println(names[0][2] + 
                           names[1][1]);
    }
}
Output:
Mr. Smith
Ms. Jones
Read more about two-dimensional array with examples at Two Dimensional Array in Java.

3. Declare an Array Example

Let's declare an integer array like:
// declares an array of integers
int[] anArray;
An array declaration has two components: the array's type and the array's name.
  1. An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty).
  2. A variable like from above program anArray is variable, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.
Few more examples for declaring an Array.
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
Employee[] anArrayOfEmployees;
Student[] anArrayOfStudent;
Object[] anArrayOfObjects;
You can also place the brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

4. Create an Array Example

One way to create an array is with the new operator.
// create an array of integers
int[] anArray = new int[10];
Above line of code allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
Few more examples to create an Array:
String[] anArrayOfStrings = new String[10];
Object[] anArrayOfObjects = new Object[10];

5. Initializing an Array Examples

Initialize Integer Array Example

Let's create and initialize integer Array with few integer elements like:
// initialize primitive one dimensional array
int[] anArray = new int[5];

anArray[0] = 10; // initialize first element
anArray[1] = 20; // initialize second element
anArray[2] = 30; // and so forth
anArray[3] = 40;
anArray[4] = 50;

Initialize String Array Example

Let's create and initialize String Array with few String elements like:
// initialize Object one dimensional array
String[] anArrayOfStrings = new String[5];
anArrayOfStrings[0] = "abc"; // initialize first element
anArrayOfStrings[1] = "xyz"; // initialize second element
anArrayOfStrings[2] = "name"; // and so forth
anArrayOfStrings[3] = "address";
anArrayOfStrings[4] = "id";

Initialize Employee Array Example

Let's create and initialize Employee Array with few employee objects:
Employee[] anArrayOfEmployees = new Employee[2];
anArrayOfEmployees[0] = new Employee(10, "ramesh");
anArrayOfEmployees[1] = new Employee(11, "john");

class Employee {
        private int id;
        private String name;

        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public Employee(int id, String name) {
                super();
                this.id = id;
                this.name = name;
        }
}

6. Accessing an Array Examples

Accessing Integer Array Example

Let's create integer Array, initialize with few elements and access integer Array with indexing.
// initialize primitive one dimensional array
int[] anArray = new int[5];

anArray[0] = 10; // initialize first element
anArray[1] = 20; // initialize second element
anArray[2] = 30; // and so forth
anArray[3] = 40;
anArray[4] = 50;

// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
System.out.println("Element 4 at index 3: " + anArray[3]);
System.out.println("Element 5 at index 4: " + anArray[4]);
Output:
Element 1 at index 0: 10
Element 2 at index 1: 20
Element 3 at index 2: 30
Element 4 at index 3: 40
Element 5 at index 4: 50

Accessing String Array Example

Let's create String Array, initialize with few elements and access String Array with indexing.
// initialize Object one dimensional array
String[] anArrayOfStrings = new String[5];
anArrayOfStrings[0] = "abc"; // initialize first element
anArrayOfStrings[1] = "xyz"; // initialize second element
anArrayOfStrings[2] = "name"; // and so forth
anArrayOfStrings[3] = "address";
anArrayOfStrings[4] = "id";

// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArrayOfStrings[0]);
System.out.println("Element 2 at index 1: " + anArrayOfStrings[1]);
System.out.println("Element 3 at index 2: " + anArrayOfStrings[2]);
System.out.println("Element 4 at index 3: " + anArrayOfStrings[3]);
System.out.println("Element 5 at index 4: " + anArrayOfStrings[4]);
Output:
Element 1 at index 0: abc
Element 2 at index 1: xyz
Element 3 at index 2: name
Element 4 at index 3: address
Element 5 at index 4: id

Accessing Employee Array Example

Let's create Employee Array, initialize with few elements and access employee Array with indexing.
Employee[] anArrayOfEmployees = new Employee[2];
anArrayOfEmployees[0] = new Employee(10, "ramesh");
anArrayOfEmployees[1] = new Employee(11, "john");

// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArrayOfEmployees[0].getName());
System.out.println("Element 2 at index 1: " + anArrayOfEmployees[1].getName());

class Employee {
        private int id;
        private String name;

        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public Employee(int id, String name) {
                super();
                this.id = id;
                this.name = name;
        }
}
Output:
Element 1 at index 0: ramesh
Element 2 at index 1: john

7. Shortcut Syntax to Create and Initialize an Array

Alternatively, we can use the shortcut syntax to create and initialize an array:
Example: Shortcut syntax to create and initialize an integer array:
// shortcut syntax to create and initialize an array
int[] array = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + array[0]);
System.out.println("Element 2 at index 1: " + array[1]);
System.out.println("Element 3 at index 2: " + array[2]);
System.out.println("Element 4 at index 3: " + array[3]);
System.out.println("Element 5 at index 4: " + array[4]);
Output:
Element 1 at index 0: 100
Element 2 at index 1: 200
Element 3 at index 2: 300
Element 4 at index 3: 400
Element 5 at index 4: 500
Shortcut syntax to create and initialize a string array example:
// shortcut syntax to create and initialize an array
String[] arrayOfStrings = {"abc", "xyz", "name", "address", "id"};
// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + arrayOfStrings[0]);
System.out.println("Element 2 at index 1: " + arrayOfStrings[1]);
System.out.println("Element 3 at index 2: " + arrayOfStrings[2]);
System.out.println("Element 4 at index 3: " + arrayOfStrings[3]);
System.out.println("Element 5 at index 4: " + arrayOfStrings[4]);
Output:
Element 1 at index 0: abc
Element 2 at index 1: xyz
Element 3 at index 2: name
Element 4 at index 3: address
Element 5 at index 4: id
Shortcut syntax to create and initialize an employee array example:
// shortcut syntax to create and initialize an array
Employee[] employees = {new Employee(10, "ramesh"),new Employee(11, "john")};
// Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + employees[0].getName());
System.out.println("Element 2 at index 1: " + employees[1].getName());
Output:
Element 1 at index 0: ramesh
Element 2 at index 1: john

8. Java Array Copy Examples(Four Ways)

Let's have a look into four different ways to copy an array in Java:
  1. Copying Arrays using Built-in System.arraycopy() Method
  2. Copying Arrays Using Arrays.copyOf() Method
  3. Copying Arrays using Object.clone() method
  4. Copying Arrays using Arrays.copyOfRange()

1. Copying Arrays using Built-in System.arraycopy() Method

/**
 * This class shows different methods for copy array in java
 * @author javaguides.net
 *
 */

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
                            'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}
The output from this program is:
caffein

2. Copying Arrays Using Arrays.copyOf() Method

If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. This method internally use System arraycopy() method.
import java.util.Arrays;

/**
 * This class shows different methods for copy array in java
 * @author javaguides.net
 *
 */
public class JavaArrayCopyExample {

        public static void main(String[] args) {
                int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                
                System.out.println("Source array = " + Arrays.toString(source));

                int[] dest = Arrays.copyOf(source, source.length);
                
                System.out.println(
                                "Copy First five elements of array. Result array = " + Arrays.toString(dest));
       }
}
Output:
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy First five elements of array. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

3. Copying Arrays using Object.clone() method

Object class provides clone() method and since an array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want a partial copy of the array.
/**
 * This class shows different methods for copy array in java
 * @author javaguides.net
 *
 */
public class JavaArrayCopyExample {

        public static void main(String[] args) {
                int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                
                System.out.println("Source array = " + Arrays.toString(source));

                int[] dest = source.clone();
                
                System.out.println(
                                "Copy First five elements of array. Result array = " + Arrays.toString(dest));
       }
}
Output:
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy First five elements of array. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9]

4. Copying Arrays using Arrays.copyOfRange()

If you want a few elements of an array to be copied, where starting index is not 0, you can use this method to copy the partial array. Again this method is also using System arraycopy method itself.
/**
 * This class shows different methods for copy array in java
 * @author javaguides.net
 *
 */
public class JavaArrayCopyExample {

        public static void main(String[] args) {
                int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                
                System.out.println("Source array = " + Arrays.toString(source));

                int[] dest = Arrays.copyOfRange(source, source.length - 3, source.length);
                
                System.out.println(
                                "Copy First five elements of array. Result array = " + Arrays.toString(dest));
       }
}
Output:
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy First five elements of array. Result array = [7, 8, 9]


9. Java Print Array Content Example

package net.javaguides.corejava.programs;

import java.util.Arrays;

public class PrintArrayExample {

    public static void main(String[] args) {

        // An array of String objects
        String[] array = new String[] {
            "First",
            "Second",
            "Third",
            "Fourth"
        };

        // Print the array using default toString method
        System.out.println(array.toString());

        // Print the array using Arrays.toString()
        System.out.println(Arrays.toString(array));

        String[] arr1 = new String[] {
            "Fifth",
            "Sixth"
        };
        String[] arr2 = new String[] {
            "Seventh",
            "Eigth"
        };

        // An array of array containing String objects
        String[][] arrayOfArray = new String[][] {
            arr1,
            arr2
        };

        // Print the array using default toString method
        System.out.println(arrayOfArray);

        // Print the array using Arrays.toString()
        System.out.println(Arrays.toString(arrayOfArray));

        // Print the array using Arrays.deepToString()
        System.out.println(Arrays.deepToString(arrayOfArray));
    }
}
Output:
[Ljava.lang.String;@7852e922
[First, Second, Third, Fourth]
[[Ljava.lang.String;@4e25154f
[[Ljava.lang.String;@70dea4e, [Ljava.lang.String;@5c647e05]
[[Fifth, Sixth], [Seventh, Eigth]]
The recommended way to print the content of an array is using Arrays.toString().

10. Advantage of Java Array

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
  • Random access: We can get any data located at any index position.

11. Limitation of an Array

  • Size Limit: We can store the only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, a collection framework is used in java.

References


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments