Arrays in Java.

By Shakib Ansari | Date: Wed, Jun 11, 2025

What is an Array in Java?

Array ek aisa data structure hota hai jo same type ke elements ko ek hi variable mein store karta hai. Jaise agar tumhare paas 5 marks hain, aur unhe tumhe store karna hai to tum kaise store karoge ? Obviously aise likhoge

int mark1 = 70;
int mark2 = 85;
int mark3 = 90;
int mark4 = 75;
int mark5 = 80;

Ab socho agar 100 students ho toh?

Solution: Array

Array ek contiguous block of memory hota hai jisme hum same type ke data ek saath store kar sakte hain — jaise 100 students ke marks, 50 names, etc.

Array Declaration:

int[] marks = new int[5];

Yeh ek 1D array hai jo 5 integers store karega.

Explain:

  1. int marks[]: Ye ek variable declare kar raha hai marks. Ye int[] indicate karte hai ki marks ek array hai jo integer values ko hold karega.
  2. = new int[5]: Ye actual array ko create karega aur marks variable ko assign kar dega.
  • new int[5]: Ye memory mein ek new array object banayega jo 5 integer values ko hold kar sake.
  • [5]: Ye array ke size ko specify karega.
  • new: 'new' java mein ek keyword hai jiska use object create karne mein hota hai.

Subscript / Index

Ye ek number hota hai jo indicate karta kisi ek particular element ki position ko within the array. Index ka use hota kisi element ko direct access karne ke liye, isse ham us element ko manipulate kar sakte hai without looping through entire array. Ye zero (0) se start hota hai jo first position ke element ko represent karta hai.

Array Initialization:

marks[0] = 70;
marks[1] = 85;
marks[2] = 90;
marks[3] = 75;
marks[4] = 80;

Example:

System.out.println(marks[1]); // 85
marks[1] = 40;
System.out.println(marks[1]); // 40

Why Use Arrays?

  • Repeated variables banane ki zarurat nahi.
  • Data par loop lagana easy hota hai.
  • Organized memory usage
  • Useful for lists, tables, etc.

Types of Arrays in Java

1. 1D Array (One-Dimensional)

1D stands for One-Dimensional Array. Ye ek single row hoti hai jo elements ko store karti hai. Ye normal array hota hai jo abhi hamne understand kare tha.

int[] scores = {90, 85, 78, 92, 88};
System.out.println(scores[2]); // Output: 78

Loop through 1D array:

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

Sum of Array Elements Program in Java

public class ArraySum {
    public static void main(String[] args) {
        // Predefined array of integers
        int[] numbers = {10, 20, 30, 40, 50};

        // Print the array elements
        System.out.print("Array elements: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }

        // Calculate the sum of the array
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }

        System.out.println("
Sum of array elements: " + sum);
    }
}
Output
Array elements: 10 20 30 40 50 
Sum of array elements: 150

2. 2D Array (Matrix Style)

2D is also stands for Two-Dimensional Array. Ye array of arrays hota hai, isko ham matrix ya table ki form mein visualize kar sakte hai. Ye grid-like structure hota hai isme element ko access karne ke liye two index use hote hai jisko indices kehte hai.

Declaration:

  • Ham ek 2D array ko declare karne ke liye data type aur two sets of square brackets ka use karte hai [][].
  • For example, int[][] matrix declare karta hai ek 2D array named matrix jo integers hold karega.
int[][] matrix; 

Array Initialize

matrix = new int[3][4]; // 3 rows, 4 columns

Yaha hamne size, rows as 3 and columns as 4 initialize kara hai.

Ham 2D array ko directly values ke sath bhi initialize kar sakte hai:

int[][] matrix = {
 {1, 2, 3},
 {4, 5, 6},
 {7, 8, 9}
};

2D Array ko kese access karte hai ?

System.out.println(matrix[1][2]); // 6

Loop through 2D Array:

for (int i = 0; i < matrix.length; i++) { // Loop through rows
    for (int j = 0; j < matrix[i].length; j++) { // Loop through columns
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}
Ouput:
1 2 3
4 5 6
7 8 9

Addition of Two Matrix Program in Java

public class MatrixAddition {
    public static void main(String[] args) {
        // Define two 2D arrays (matrices)
        int[][] matrix1 = {
            {1, 2, 3},
            {4, 5, 6}
        };

        int[][] matrix2 = {
            {7, 8, 9},
            {10, 11, 12}
        };

        // Get the dimensions
        int rows = matrix1.length;
        int cols = matrix1[0].length;

        // Create a new matrix to store the sum
        int[][] sum = new int[rows][cols];

        // Perform addition
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                sum[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }

        // Display the result
        System.out.println("Sum of the two matrices:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Output:
Sum of the two matrices:
8 10 12 
14 16 18 

Jugged Array:

Jugged Array arrays ka ek array hota hai. Jisme har ek inner array ki length different ho sakti hai. Unlike 2D array jisme sabhi rows mein same number of columns hote hai. Jugged array, ek array ki har row mein flexibility ko allow karta hai.

Declaration and Initialization:

int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2};
jagged[1] = new int[]{3, 4, 5};
jagged[2] = new int[]{6};

Loop through jagged array:

for (int i = 0; i < jagged.length; i++) {
  for (int j = 0; j < jagged[i].length; j++) {
    System.out.print(jagged[i][j] + " ");
  }
  System.out.println();
}
Output:
1 2
3 4 5
6

Students Marks with Subject Program in Java

public class StudentMarksJaggedArray {
  public static void main(String[] args) {
    // Each row represents one student
    // Each student has a different number of subjects (jagged structure)
    int[][] studentMarks = {
      {85, 78, 92},     // Student 1: 3 subjects
      {90, 88},       // Student 2: 2 subjects
      {75, 70, 80, 90},   // Student 3: 4 subjects
      {60}         // Student 4: 1 subject
    };

    // Display the data
    for (int i = 0; i < studentMarks.length; i++) {
      System.out.print("Student " + (i + 1) + " marks: ");
      for (int j = 0; j < studentMarks[i].length; j++) {
        System.out.print(studentMarks[i][j] + " ");
      }
      System.out.println();
    }

    // Calculate and display average marks for each student
    System.out.println("
Average Marks:");
    for (int i = 0; i < studentMarks.length; i++) {
      int sum = 0;
      for (int mark : studentMarks[i]) {
        sum += mark;
      }
      double avg = (double) sum / studentMarks[i].length;
      System.out.println("Student " + (i + 1) + ": " + avg);
    }
  }
}
Output:
Student 1 marks: 85 78 92 
Student 2 marks: 90 88 
Student 3 marks: 75 70 80 90 
Student 4 marks: 60 


Average Marks:
Student 1: 85.0
Student 2: 89.0
Student 3: 78.75
Student 4: 60.0


About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments