Introduction
An array in Java is a data structure that allows you to store multiple values of the same type in a single variable. Arrays are a fundamental part of Java programming and provide a way to manage large amounts of data efficiently. In this chapter, we will explore the syntax, usage, and examples of arrays in Java.
Table of Contents
- Declaration and Initialization
- Accessing Array Elements
- Iterating Over Arrays
- Array Length
- Multi-Dimensional Arrays
- Common Array Operations
- Additional Array Programs
1. Declaration and Initialization
Syntax
There are several ways to declare and initialize an array in Java.
Declaration
dataType[] arrayName;
Initialization
You can initialize an array when you declare it, or separately.
Combined Declaration and Initialization:
int[] numbers = {1, 2, 3, 4, 5};
Separate Declaration and Initialization:
int[] numbers;
numbers = new int[5]; // Creates an array of integers with 5 elements
Initialization with Values:
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
Example: Declaration and Initialization
public class ArrayExample {
public static void main(String[] args) {
// Combined declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
// Separate declaration and initialization
String[] fruits;
fruits = new String[3];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Cherry";
}
}
2. Accessing Array Elements
Array elements are accessed using their index, which starts from 0.
Syntax
arrayName[index];
Example: Accessing Elements
public class AccessArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Access and print the first element
System.out.println("First element: " + numbers[0]);
// Access and print the second element
System.out.println("Second element: " + numbers[1]);
}
}
Output
First element: 1
Second element: 2
3. Iterating Over Arrays
You can iterate over arrays using loops such as for
, while
, and for-each
.
Example: Using for Loop
public class ForLoopArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Iterate over the array using a for loop
for (int i = 0; i < numbers.length; i++) {
// Print the current element of the array
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
Example: Using for-each Loop
public class ForEachArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Iterate over the array using a for-each loop
for (int number : numbers) {
// Print the current element of the array
System.out.println("Number: " + number);
}
}
}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
4. Array Length
The length of an array can be determined using the length
property.
Example: Array Length
public class ArrayLengthExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Print the length of the array
System.out.println("Length of the array: " + numbers.length);
}
}
Output
Length of the array: 5
5. Multi-Dimensional Arrays
Java supports multi-dimensional arrays, such as 2D arrays.
Declaration and Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Example: Accessing 2D Array Elements
public class MultiDimensionalArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access and print elements of the 2D array
System.out.println("Element at row 1, column 1: " + matrix[0][0]);
System.out.println("Element at row 2, column 3: " + matrix[1][2]);
}
}
Output
Element at row 1, column 1: 1
Element at row 2, column 3: 6
Example: Iterating Over 2D Array
public class IterateMultiDimensionalArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Iterate over the 2D array using nested for loops
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
// Print the current element of the 2D array
System.out.println("Element at row " + i + ", column " + j + ": " + matrix[i][j]);
}
}
}
}
Output
Element at row 0, column 0: 1
Element at row 0, column 1: 2
Element at row 0, column 2: 3
Element at row 1, column 0: 4
Element at row 1, column 1: 5
Element at row 1, column 2: 6
Element at row 2, column 0: 7
Element at row 2, column 1: 8
Element at row 2, column 2: 9
6. Common Array Operations
Example: Finding the Maximum Element
public class MaxArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int max = numbers[0];
// Iterate over the array to find the maximum element
for (int num : numbers) {
if (num > max) {
max = num;
}
}
// Print the maximum element
System.out.println("Maximum element: " + max);
}
}
Output
Maximum element: 5
Example: Summing Elements in an Array
public class SumArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
// Iterate over the array to calculate the sum of elements
for (int num : numbers) {
sum += num;
}
// Print the sum of elements
System.out.println("Sum of elements: " + sum);
}
}
Output
Sum of elements: 15
Example: Reversing an Array
public class ReverseArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.length;
// Iterate over the array to reverse it
for (int i = 0; i < length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[length - 1 - i];
numbers[length - 1 - i] = temp;
}
// Print the reversed array
System.out.print("Reversed array: ");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
Output
Reversed array: 5 4 3 2 1
7. Additional Array Programs
Example: Checking if an Array is Sorted
public class CheckSortedArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Method to check if the array is sorted
boolean isSorted = true;
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
isSorted = false;
break;
}
}
// Print whether the array is sorted or not
if (isSorted) {
System.out.println("The array is sorted.");
} else {
System.out.println("The array is not sorted.");
}
}
}
Output
The array is sorted.
Example: Merging Two Arrays
public class MergeArraysExample {
public static void main(String[] args) {
int[] array1 = {1, 3, 5};
int[] array2 = {2, 4, 6};
// Merge the two arrays
int[] mergedArray = new int[array1.length + array2.length];
int index = 0;
for (int i = 0; i < array1.length; i++) {
mergedArray[index++] = array1[i];
}
for (int i = 0; i < array2.length; i++) {
mergedArray[index++] = array2[i];
}
// Print the merged array
System.out.print("Merged array: ");
for (int num : mergedArray) {
System.out.print(num + " ");
}
}
}
Output
Merged array: 1 3 5 2 4 6
Example: Removing Duplicates from an Array
import java.util.Arrays;
public class RemoveDuplicatesArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 2, 3, 4, 4, 5};
// Sort the array
Arrays.sort(numbers);
// Remove duplicates
int[] tempArray = new int[numbers.length];
int j = 0;
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] != numbers[i + 1]) {
tempArray[j++] = numbers[i];
}
}
tempArray[j++] = numbers[numbers.length - 1];
// Create an array with the new length
int[] uniqueNumbers = Arrays.copyOf(tempArray, j);
// Print the array without duplicates
System.out.print("Array without duplicates: ");
for (int num : uniqueNumbers) {
System.out.print(num + " ");
}
}
}
Output
Array without duplicates: 1 2 3 4 5
Example: Finding the Second Largest Element in an Array
public class SecondLargestArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Method to find the second largest element
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : numbers) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
// Print the second largest element
System.out.println("Second largest element: " + secondLargest);
}
}
Output
Second largest element: 4
Conclusion
Arrays in Java are a powerful and versatile data structure that allows you to store and manipulate multiple values of the same type efficiently. Understanding how to declare, initialize, access, and iterate over arrays is fundamental to Java programming. Additionally, knowing how to perform common array operations such as finding the maximum element, summing elements, and reversing the array will enhance your ability to work with arrays effectively. By practicing with additional array programs, you can further solidify your understanding and improve your problem-solving skills.