Java Arrays

Java Array is used to hold multiple values of same data type in a variable. This helps in avoiding the creation of multiple variables to store data of similar category.

Usually the value of array starts with the index 0.

Example

String[] users = new String[100];

In the above syntax, we have created a string array users which can hold 100 values in it.

Here, the size of users array starts from 0 to 99.

Declaring an array

There are different ways to create an array

// Method 1
double[] value;
value = new double[100];

// Method 2
double[] value = new double[100];

Initializing an array

There are two ways to initialize values to an array.

First, we can provide value to an array when you declare the array.

Example

String[] names = {"Andrew", "John", "Peter"};

In the above method, the values are assigned to the names array during initialization.

Second, we can declare an array with its size and later we provide values to the array.

Example

String[] names = new names[5];
names[0] = "Andrew";
names[1] = "John";
names[2] = "Peter";

Accessing the array values

An array's element can be accessed using the index number. The syntax for accessing an array's elements is shown below.

Syntax

array[index];

Example to access array elements

class Main {
 public static void main(String[] args) {
  
   // create an array
   String[] names = {"Andrew", "John", "Peter"};

   // access each array elements
   System.out.println("List of users:");
   System.out.println(names[0]);
   System.out.println(names[1]);
   System.out.println(names[2]);
 }
}

Output

List of users:
Andrew
John
Peter

Let us see an example program to find the sum of elements in an array using the for loop.

Example to loop through array

class Main {
 public static void main(String[] args) {
  
   // create an array
   int[] numbers = {1,3,4,5,6,7,4,23,5};
    int sum = 0;
   for(int i=0;i<numbers.length;i++){
       sum+=numbers[i];
   }
    System.out.printf("Sum is %d",sum);
 }
}

Output

Sum is 58

In the above program, numbers array has been declared with initial set of numbers.

The variable sum is used to store the result by adding the values of the numbers array.

Next, using the for loop we loop through the numbers array starting with the index position 0 to the size of the array and add the value to the sum variable.

Example to access array using for-each loop

class Main {
 public static void main(String[] args) {
  
   // create an array
   int[] numbers = {1,3,4,5,6,7,4,23,5};
    int sum = 0;
   for(int number: numbers)
   {
       sum+=number;
   }
    System.out.printf("Sum is %d",sum);
 }
}

Output

  Sum is 58

Most Read