C

Core Java tutorial for beginners

Clean • Professional

Java Array Examples – Practical Examples for Beginners

3 minute

Java Array Examples – Practical Examples for Beginners

Arrays are one of the core building blocks in Java. Understanding practical examples helps you master array operations quickly.


1. Example: Printing Array Elements

Printing all elements of an array is one of the most common operations. You can use a for loop or enhanced for-each loop.

Using For Loop

public class PrintArray {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println("Printing using for loop:");
        for(int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Using For-Each Loop

System.out.println("Printing using for-each loop:");
for(int num : numbers) {
    System.out.println(num);
}

Output:

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
10
20
30
40
50

2. Example: Finding Maximum and Minimum in an Array

Finding the largest and smallest element is a common array task.

Example

public class MaxMinArray {
    public static void main(String[] args) {
        int[] numbers = {10, 45, 32, 67, 21};

        int max = numbers[0];
        int min = numbers[0];

        for(int num : numbers) {
            if(num > max) max = num;
            if(num < min) min = num;
        }

        System.out.println("Maximum value: " + max);
        System.out.println("Minimum value: " + min);
    }
}

Output:

Maximum value: 67
Minimum value: 10

3. Example: Summing Array Elements

Summing elements is a basic but important operation, often used in real-world programs.

Example

public class SumArray {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        int sum = 0;
        for(int num : numbers) {
            sum += num;
        }

        System.out.println("Sum of array elements: " + sum);
    }
}

Output:

Sum of array elements: 150

 

Article 0 of 0