Java Array Tutorial – Creating, Initializing, and Accessing Array in Java

1. Objective

In our last tutorial, we talked about Java Number Method. Here, we are going to explore the Java Array Tutorial, in which we learn: How to create a Java array. initialize arrays in Java, and access Java arrays. At last, we cover the java array examples.

So, let’s start the Java Array Tutorial.

Java Array Tutorial - Creating, Initializing, and Accessing Array in Java

Java Array Tutorial – Creating, Initializing, and Accessing Array in Java

2. What is Java Array

Arrays in Java are a group of same type variables that are referred under a common name. Features of Java arrays that make it different from arrays used in C and C++ are

  • All Java array is dynamically allocated.
  • Arrays are treated as Java objects so, their length can found using member length, while C/C++ size of was used.
  • The variables of Java arrays can declare like any other variable, i.e. after the datatype.
  • The indexing starts from zero.
  • Array in Java can use as a static field, a local variable, and a method parameter.
  • In Java, size on an array can only specify by int type and no other type.
  • The object is the direct superclass in Java.

In Java, array primitive datatype, as well as objects, can store when a primitive datatype is stored than the actual values are stored at the memory locations while when objects are stored than actual objects are stored in heap segments.

Java Array - Introduction

Introduction of Java Array with Example

3. Creating, Initializing, and Accessing Java Array

a. One-Dimensional Array

One-dimensional array in Java is usually declared as

type var-name[];

OR

type[] var-name;

It has two parts – first being the type which declares the element type of the array in java. But first, let’s revise Java Syntax for better understanding.
Example 

// both are valid declarations
int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
// an array of references to objects of the class MyClass (a class created by user)
MyClass myClassArray[];
Object[]  ao,        // array of Object
Collection[] ca;  // array of Collection of unknown type

b. Instantiating an Array in Java

The general form of a Java array is

var-name = new type [size];

Size here specifies the number of elements while var name specifies the name of array.

Example

int intArray[];    //declaring array
intArray = new int[20];  // allocating memory to array

c. Array Literal

When the size of the array is already known to us, then we can use the array literals in Java.
Example

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
 // Declaring array literal

d. Accessing Array Elements using for Loop

All the elements can access via for loops in Java, an element can access via index of the Java array, it starts from zero and ends at a total number of elements -1.
Syntax

// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
  System.out.println("Element at index " + i +
                                " : "+ arr[i]);

Example 

// Java program to illustrate creating an array of integers puts some values in the array, and prints each value to standard output.
class GFG
{
    public static void main (String[] args)
    {        
      // declares an Array of integers.
      int[] arr;
      // allocating memory for 5 integers.
      arr = new int[5];
      // initialize the first element of the array
      arr[0] = 10;
      // initialize the second element of the array
      arr[1] = 20;
      //so on...
      arr[2] = 30;
      arr[3] = 40;
      arr[4] = 50;
       // accessing the elements of the specified array
      for (int i = 0; i < arr.length; i++)
         System.out.println("Element at index " + i +
                                      " : "+ arr[i]);        
    }
}
One Dimensional Array - Java Array

One Dimensional Array in Java

e. Array of Objects

An array of objects creates just like an array of a datatype in Java.

Do you Know Array vs ArrayList in Java 

Syntax

Student[] arr = new Student[7]; //student is a user-defined class

Example

// Java program to illustrate creating an array of objects
class Student
{
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
}
public class GFG
{
    public static void main (String[] args)
    {
        Student[] arr;
         arr = new Student[5];
         arr[0] = new Student(1,"ayushi");
         arr[1] = new Student(2,"nainsih");
         arr[2] = new Student(3,"mohnish");
         arr[3] = new Student(4,"anshul");
         arr[4] = new Student(5,"Aparna");
         for (int i = 0; i < arr.length; i++)
         System.out.println("Element at " + i + " : " +
          arr[i].roll_no +" "+ arr[i].name);
    }
}

f. Java Multidimensional Array

Multi-dimensional arrays are basically arrays of arrays, they are also called Jagged arrays in java.
Syntax

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

Example

class multiDimensional
{
    public static void main(String args[])
    {
        // declaring and initializing 2D array
        int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
        // printing 2D array
        for (int l=0; l< 4 ; i++)
        {
            for (int k=0; k< 4 ; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}

Java Multidimensional Array

Follow this link to know about Multithreading in Java

g. Passing Array to Method

// Java program to demonstrate passing of array to method
class Test
{  
    // Driver method
    public static void main(String args[])
    {
        int arr[] = {3, 1, 2, 5, 4};       
        // passing array to method m1
        sum(arr);
         }
    public static void sum(int[] arr)
    {
        // getting sum of array values
        int sum = 0;       
        for (int i = 0; i < arr.length; i++)
        sum+=arr[i];       
        System.out.println("sum of array values : " + sum);
    }
}

h. Returning Array from Method

// Java program to demonstrate return of array from method
class Test
{  
    // Driver method
    public static void main(String args[])
    {
        int arr[] = m1();    
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i]+" ");
        }
    public static int[] m1()
    {
        // returning  array
        return new int[]{1,2,3};
    }
}

i.  Cloning of Array

In a single dimensional array, a ‘deep copy’ creates that is clones of the original elements or reference elements creates.
Example

// Java program to demonstrate cloning of one-dimensional arrays
class Test
{  
    public static void main(String args[])
    {
         int intArray[] = {1,2,3};
         int cloneArray[] = intArray.clone();
         // will print false as deep copy is created for one-dimensional array
         System.out.println(intArray == cloneArray);
         for (int i = 0; i < cloneArray.length; i++)
 {
            System.out.print(cloneArray[i]+" ");
        }
    }
}
Java Array - Clone method

Java Array – Deep Copy For One Dimensional Array

Do you know How to Declare and Call a Java Method

Deep Copy Of One Dimensional Array by Clone Method
In a multi-dimensional array in java when cloning is done a ‘shallow copy’ is created that is, it creates only a single Java new array for every reference array, but subarrays share.
Example

// Java program to demonstrate cloning of multi-dimensional arrays
class Test
{  
    public static void main(String args[])
    {
          int intArray[][] = {{1,2,3},{4,5}};      
          int cloneArray[][] = intArray.clone();
          // will print false
          System.out.println(intArray == cloneArray);
          // will print true as shallow copy is created i.e. sub-arrays are shared
          System.out.println(intArray[0] == cloneArray[0]);
          System.out.println(intArray[1] == cloneArray[1]);
    }
}
Java Array - Copy by Clone Method

Java Array – Shallow Copy for Multidimensional Array by Clone Method

So, this was all about Java Array Tutorial. Hope you like our explanation.

Java Quiz

4.  Conclusion

Hence, we learned about array in java, array declaration, initialization of array, types of java array and many other things. Java Arrays are a very important part of Java programming. Is this information helps you? Share your feedback with us!
See Also – Method Overloading vs Overriding in Java
For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.