Introduce Java Arrays and give examples
Java arrays are a fundamental data structure that allows you to store multiple values of the same type in a single variable. They are fixed in size, meaning that once you create an array, you cannot change its size. Arrays can hold primitive data types (like int
, char
, double
, etc.) as well as objects.
0
, the second with index 1
, and so on.You can declare an array in Java using the following syntax:
dataType[] arrayName; // Declaration
You can initialize an array in several ways:
Static Initialization:
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
String[] fruits = {"Apple", "Banana", "Cherry"}; // Array of strings
Dynamic Initialization:
int[] numbers = new int[5]; // Creates an array of integers with 5 elements
You can access elements in an array using their index:
int firstNumber = numbers[0]; // Accessing the first element
String firstFruit = fruits[0]; // Accessing the first fruit
Here’s a simple example that demonstrates how to declare, initialize, and manipulate an array in Java:
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};
// Accessing and printing elements of the array
System.out.println("First number: " + numbers[0]); // Output: 10
System.out.println("Second number: " + numbers[1]); // Output: 20
// Modifying an element in the array
numbers[2] = 35; // Changing the third element from 30 to 35
System.out.println("Modified third number: " + numbers[2]); // Output: 35
// Looping through the array
System.out.println("All numbers in the array:");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Using enhanced for loop
System.out.println("Using enhanced for loop:");
for (int number : numbers) {
System.out.println(number);
}
}
}
First number: 10
Second number: 20
Modified third number: 35
All numbers in the array:
10
20
35
40
50
Using enhanced for loop:
10
20
35
40
50
Java arrays are a powerful way to store and manipulate collections of data. They provide a simple and efficient way to manage multiple values of the same type, making them a fundamental part of Java programming.