Provide Best Programming Tutorials

Introduction To Array In Java

Introduction To Array In Java

An array is used to store a collection of data, but often we find it more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1,. . . , and number99, you declare one array variable such as numbers and use numbers[0], numbers[1],. . . , and numbers[99] to represent individual variables. This section introduces how to declare array variables, create arrays, and process arrays using indexes.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array and specify the array’s element type. Here is the syntax for declaring an array variable:

dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.

The element type can be any data type, and all elements in the array will have the same data type. For example, the following code declares a variable myList that references an array of double elements.

double[] myList;

Creating Arrays

Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. If a variable does not contain a reference to an array, the value of the variable is null. You cannot assign elements to an array unless it has already been created.

You can create an array by using the new operator and assign its reference to the variable with the following syntax:

arrayRefVar = new elementType[arraySize];

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement as:

elementType[] arrayRefVar = new elementType[arraySize];

or

elementType arrayRefVar[] = new elementType[arraySize];

double[] myList = new double[10];

This statement declares an array variable, myListcreates an array of ten elements of double type, and assigns its reference to.myList To assign values to the elements, use the syntax:

arrayRefVar[index] = value;

For example, the following code initializes the array.

myList[0] = 5.6;
myList[1] = 4.5;
myList[2] = 3.3;
myList[3] = 13.2;
myList[4] = 4.0;
myList[5] = 34.33;
myList[6] = 34.0;
myList[7] = 45.45;
myList[8] = 99.993;
myList[9] = 11123;

The array myList has ten elements of double type and int indices from 0 to 9 .

Array Size and Default Values

When space for an array is allocated, the array size must be given, specifying the number of elements that can be stored in it. The size of an array cannot be changed after the array is created.

Size can be obtained using arrayRefVar.length. For example, myList.length is 10. When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, Äu0000 for char types, and false for boolean types.

/**
 * Determine the Java array length, i.e.,
 * the length of a Java array.
 * @author alvinalexander.com
 *
 */
public class JavaArrayLengthExample
{

  public static void main(String[] args) {
      String[] toppings = {"cheese", "pepperoni", "black olives"};
      int arrayLength = toppings.length;
      System.out.format("The Java array length is %d", arrayLength);
  }

}

Accessing Array Elements

// create an array of integers 
anArray = new int[10];

anArray[0] = 100; // initialize first element 
anArray[1] = 200; // initialize second element 
anArray[2] = 300; // and so forth

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]);

Iterate Array

Three ways to do this:

  • Using for-each loop
  • Using normal for loop

Using for-each loop

//define an array
int a[];
//create an array
a = new int[5];

a[4] = 5;
a[3] = 4;
a[2] = 3;
a[1] = 2;
a[0] = 1;

//show initial value of an array
for (int item : a) {
    System.out.print(item + " ");
}

Using normal for loop

//define an array
int a[];
//create an array
a = new int[5];

a[4] = 5;
a[3] = 4;
a[2] = 3;
a[1] = 2;
a[0] = 1;

       

for (int i=0;i<a.length;i++){
    System.out.println(i);
}

Copy An Array

To copy the contents of one array into another, you have to copy the array’s individual elements into the other array.

Often, in a program, you need to duplicate an array or a part of an array. In such cases, you could attempt to use the assignment statement (=), as follows:

list2 = list1;

But unfortunately this will not copy an array but just give the reference of the array as fixture below shows: now reference andlist1 list2 all point to the same array content.

So how could we copy an array? Java provides three ways to do:

  • Using the for loop to copy each element in the old array to the new one
  • Using the arraycopy method
  • Using the clone method

Using for loop

public static int[] copyAnArray(int src[]) {
       int des[] = new int[src.length];
       for (int i = 0; i < src.length; i++) {
           des[i] = src[i];
       }
       return des;
   }

Using arraycopy method

class ArrayCopyOfDemo {
    public static void main(String[] args) {
        
        char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',
            'i', 'n', 'a', 't', 'e', 'd'};
            
        char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
        
        System.out.println(new String(copyTo));
    }
}

Using clone() method

int a[] = {1, 3, 5, 7, 8};
int[] c = a.clone();

Leave a Reply

Close Menu