Clean • Professional
Arrays are one of the core building blocks in Java. Understanding practical examples helps you master array operations quickly.
Printing all elements of an array is one of the most common operations. You can use a for loop or enhanced for-each 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]);
}
}
}
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
Finding the largest and smallest element is a common array task.
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
Summing elements is a basic but important operation, often used in real-world programs.
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