Java Arrays

📦 Java Arrays

An array in Java is a container object that holds a fixed number of values of the same type.
Arrays are zero-indexed, meaning the first element is at index 0.


✅ 1. Declaration and Initialization

Syntax:

dataType[] arrayName; // Declaration
arrayName = new dataType[size]; // Memory allocation

Or combined:

dataType[] arrayName = new dataType[size];

Example 1: Declare an integer array

public class Main {
public static void main(String[] args) {
int[] numbers = new int[5]; // size = 5

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

System.out.println(numbers[2]); // 30
}
}


Example 2: Declare and initialize together

public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Orange"};

System.out.println(fruits[0]); // Apple
System.out.println(fruits[2]); // Orange
}
}


✅ 2. Array Length

int[] numbers = {10, 20, 30, 40};
System.out.println("Array length: " + numbers.length);

📌 Output:

Array length: 4

✅ 3. Looping Through an Array

Using for loop:

int[] numbers = {10, 20, 30, 40};

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

Using for-each loop:

for (int num : numbers) {
System.out.println(num);
}

✅ 4. Array of Objects (Strings Example)

String[] cars = {"BMW", "Audi", "Tesla"};

for (String car : cars) {
System.out.println(car);
}

📌 Output:

BMW
Audi
Tesla

✅ 5. Multidimensional Arrays (2D Array)

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

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

Looping through 2D array:

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

📌 Output:

1 2 3
4 5 6
7 8 9

✅ 6. Common Array Operations

Operation Example
Sum of elements for (int num : numbers) sum += num;
Find max/min int max = numbers[0]; then loop to compare
Copy array int[] copy = Arrays.copyOf(numbers, numbers.length);
Sort array Arrays.sort(numbers);

🧠 Summary

  • Arrays store fixed-size collections of same-type elements.

  • Single-dimensional arrays → List of elements.

  • Multidimensional arrays → Matrix-like structure.

  • Access using index starting from 0.

  • Can loop with for or for-each.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

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