6.1 Declaring and Initializing Arrays:
- Arrays are used to store multiple values of the same data type in a single variable. Here's how you can declare and initialize an array:
class ArrayDeclarationInit{
public static void main(String[] args) {
// Declaring an array of integers
int[] numbers;
// Initializing the array with values
numbers = new int[]{1, 2, 3, 4, 5};
}
}
6.2 Accessing Array Elements:
- You can access individual elements in an array using their index. The index starts from 0 for the first element.
class ArrayAccessingExample{
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Accessing the first element
int firstNumber = numbers[0];
System.out.println("firstNumber"+ firstNumber);// firstNumber: 1
// Accessing the third element
int thirdNumber = numbers[2];
System.out.println("thirdNumber"+ thirdNumber);// thirdNumber: 3
}
}
6.3 Array Length and Enhanced for Loop:
- You can get the length of an array using the “length” property.
- It represents the number of elements in the array.
class Arraylength{
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Getting the length of the array
int length = numbers.length;
System.out.println("length"+"="+ length); // length = 5
}
}
- The enhanced for loop, also known as the foreach loop, simplifies iterating over all elements in an array.
class MultiArrayFor{
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Printing all elements using the enhanced for loop
for (int number : numbers) {
System.out.println(number);
}
}
}
6.4 Multidimensional Arrays:
Arrays can have multiple dimensions, allowing you to create tables or matrices.
class MultiArray{
public static void main(String[] args) {
// Declaring and initializing a 2D array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing an element in a 2D array
int element = matrix[1][2];
System.out.println("element"+":"+ element); // element: 6
}
}