Welcome to The Coding College! In this tutorial, we’ll dive into Java Arrays, a fundamental concept for managing and storing data efficiently in programming. Arrays allow you to store multiple values in a single variable, simplifying the process of working with large datasets.
What is an Array?
An array is a data structure that can hold a fixed number of elements of the same type.
- The elements in an array are stored at contiguous memory locations.
- Each element is accessed using an index, starting from
0
.
Syntax
dataType[] arrayName; // Declares an array
arrayName = new dataType[size]; // Allocates memory for the array
Alternatively, you can combine the declaration and allocation:
dataType[] arrayName = new dataType[size];
Example: Creating and Initializing an Array
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // Array initialization
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
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
Types of Arrays
1. Single-Dimensional Array
A single-dimensional array is a linear collection of elements.
Syntax
dataType[] arrayName = new dataType[size];
Example
public class SingleDimensionalArray {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
2. Multi-Dimensional Array
A multi-dimensional array stores data in rows and columns, resembling a matrix.
Syntax
dataType[][] arrayName = new dataType[rows][columns];
Example
public class MultiDimensionalArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
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
Common Operations on Arrays
1. Access Elements
Access elements using their index:
int element = arrayName[index];
2. Update Elements
Modify the value at a specific index:
arrayName[index] = newValue;
3. Find Length of an Array
Use the length
property:
int length = arrayName.length;
4. Iterate Over an Array
Using a for
Loop
for (int i = 0; i < arrayName.length; i++) {
System.out.println(arrayName[i]);
}
Using a for-each
Loop
for (dataType element : arrayName) {
System.out.println(element);
}
Practice Problems
- Write a program to find the largest and smallest numbers in an array.
- Create a two-dimensional array to store and display a multiplication table.
- Reverse the elements of an array and print the result.
Key Points
- Arrays in Java are zero-indexed.
- The size of an array is fixed once defined.
- Use arrays to store and manipulate collections of similar data efficiently.
For more tutorials and coding tips, visit The Coding College. Stay consistent and keep coding your way to success! 🚀