Arrays in Java with Program Examples

Arrays in Java are a group of like-typed variables that are referred to by a common name. Array is a collection of similar type of elements that have contiguous memory location.

Following are some important point about Java arrays.

  • Arrays in Java are Objects.
  • In Java all arrays are dynamically allocated.(discussed below)
  • 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.
  • The direct superclass of an array type is Object.
  • Array can contains primitives data types as well as objects of a class depending on the definition of array.
  • In case of primitives data types, the actual values are stored in contiguous memory locations.
  • In case of objects of a class, the actual objects are stored in heap segment.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array
Single Dimensional Arrays
Creating, Initializing, and Accessing an Array

The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;

An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like array of int type, we can also create an array of other primitive data types like char, float, double..etc or user defined data type(objects of a class).

Example:

// both are valid declarations
int intArray[]; 
or int[] intArray; 

byte byteArray[];
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

Although the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.

Instantiating an Array in Java

When an array us declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and var-name is the name of array variable that is linked to the array. That is, to use new to allocate an array, you must specify the type and number of elements to allocate.

Example:

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

OR

int[] intArray = new int[20]; // combining both statements in one

Note :

  1. The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types).Refer Default array values in Java
  2. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory that will hold the array, using new, and assign it to the array variable. Thus, in Java all arrays are dynamically allocated.

In a situation, where the size of the array and variables of array are already known, array literals can be used.

 int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; 
 // Declaring array literal
  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java

Lets see one more program example of Java Arrays –

class Testarray {
 public static void main(String args[]) {

  int a[] = new int[5]; //declaration and instantiation  
  a[0] = 10; //initialization  
  a[1] = 20;
  a[2] = 70;
  a[3] = 40;
  a[4] = 50;

  //printing array  
  for (int i = 0; i < a.length; i++) //length is the property of array  
   System.out.println(a[i]);

 }
}
Output
Output: 10
20
70
40
50
Arrays of Objects

An array of objects is created just like an array of primitive type data items in the following way. Lets see a program example –

Lets see a program example on Array Of Objects in Java –

class Student
{
    public int roll_no;
    public String name;
    Student(int roll_no, String name)
    {
        this.roll_no = roll_no;
        this.name = name;
    }
}
 
// Elements of array are objects of a class Student.
public class GFG
{
    public static void main (String[] args)
    {
        // declares an Array of integers.
        Student[] arr;
 
        // allocating memory for 5 objects of type Student.
        arr = new Student[5];
 
        // initialize the first elements of the array
        arr[0] = new Student(1,"aman");
 
        // initialize the second elements of the array
        arr[1] = new Student(2,"vaibhav");
 
        // so on...
        arr[2] = new Student(3,"shikar");
        arr[3] = new Student(4,"dharmesh");
        arr[4] = new Student(5,"mohit");
 
        // accessing the elements of the specified array
        for (int i = 0; i < arr.length; i++)
            System.out.println("Element at " + i + " : " +
                        arr[i].roll_no +" "+ arr[i].name);
    }
}
Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

 

One thought on “Arrays in Java with Program Examples

Leave a Reply

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