Java Tutorial menu

Java Arrays

An array stores many values of the same type in one variable.

Creating an Array

Put the values inside curly braces, and add [] after the type:

Example

java
String[] students = {"Ali", "Ayesha", "Bilal", "Sana"};
int[] marks = {78, 91, 64, 85};

You can also create an empty array of a fixed size. Every item starts with a default value (0 for numbers, null for objects):

Example

java
int[] scores = new int[5];   // five zeros

Reading and Changing Items

Each item has an index. The first item is at index 0.

Example

java
public class Main {
  public static void main(String[] args) {
    String[] students = {"Ali", "Ayesha", "Bilal", "Sana"};

    System.out.println(students[0]);
    System.out.println(students[2]);

    students[2] = "Hamza";
    System.out.println(students[2]);
    System.out.println("Total: " + students.length);
  }
}
Output
Ali
Bilal
Hamza
Total: 4
CodeMeaning
arr[0]The first item
arr[arr.length - 1]The last item
arr.lengthHow many items (no brackets, it is not a method)

Using an index that does not exist, like students[4] in an array of 4 items, crashes the program with an ArrayIndexOutOfBoundsException.

Looping Through an Array

Use a for loop when you need the index, or a for-each loop when you only need the values:

Example

java
public class Main {
  public static void main(String[] args) {
    int[] marks = {78, 91, 64, 85};
    int total = 0;

    for (int i = 0; i < marks.length; i++) {
      System.out.println("Student " + (i + 1) + ": " + marks[i]);
      total += marks[i];
    }

    System.out.println("Average: " + (total / (double) marks.length));
  }
}
Output
Student 1: 78
Student 2: 91
Student 3: 64
Student 4: 85
Average: 79.5

Finding the Highest Value

Example

java
int[] prices = {350, 1200, 799, 450};
int highest = prices[0];
for (int p : prices) {
  if (p > highest) {
    highest = p;
  }
}
System.out.println("Highest: Rs " + highest);
Output
Highest: Rs 1200

Sorting and Printing with Arrays

The java.util.Arrays class has ready-made helpers:

Example

java
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] nums = {5, 2, 9, 1};
    Arrays.sort(nums);
    System.out.println(Arrays.toString(nums));
  }
}
Output
[1, 2, 5, 9]

Two-Dimensional Arrays

A 2D array is an array of arrays, like a table with rows and columns:

Example

java
int[][] seats = {
  {1, 2, 3},
  {4, 5, 6}
};
System.out.println(seats[1][2]);   // row 1, column 2
Output
6

Exercise

Exercise

An array has 6 items. What is the index of the last item?

Learn Java with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp