Arrays in Java:
In Java, an array is a data structure that allows you to store multiple values of the same data type in a single variable.
Arrays are widely used to work with collections of data. Arrays is a fundamental concept in Java programming.
Advantages of Arrays:
- Represent multiple data items of the same type in a single variable.
- Arrays have a fixed size that is defined when they are initialized.
- Arrays can easily be iterated through using loops, making it convenient to perform operations on all elements in the array sequentially.
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 33, 25, 12, 29};
}
}
Accessing elements in Arrays:
We can access elements in Arrays using indexes. Indexes start from zero. Zeroth element is considered the first element and n-1th element is the last element.
public class Main {
public static void main(String[] args) {
int[] numbers = {90, 36, 45, 77, 32};
System.out.println(numbers[0]);
System.out.println(numbers[1]);
System.out.println(numbers[2]);
System.out.println(numbers[3]);
System.out.println(numbers[4]);
}
}
Changing elements in Arrays:
We can reassign value to elements in arrays.
public class Main {
public static void main(String[] args) {
int[] numbers = {33, 65, 34, 66, 90};
numbers[0] = 100;
System.out.println(numbers[0]);
}
}
Length of Arrays:
We can find the length of an array using length function.
public class Main {
public static void main(String[] args) {
int[] numbers = {23, 76, 44, 20, 89};
System.out.println(numbers.length);
}
}
Iterating through Arrays:
We can iterate through the elements of arrays using for loop and for each loop.For loop:
We can iterate through elements of array using for loop.
public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Fig"};
for(int i = 0; i < fruits.length; i++){
System.out.println(fruits[i]);
}
}
}
For each loop:
We can also iterate through elements of array using for each loop.
public class Main {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Fig"};
for(String fruit : fruits){
System.out.println(fruit);
}
}
}
Two Dimensional Arrays:
A 2-Dimensional array in Java is essentially an array of arrays, where each element of the main array is itself an array. This creates a grid-like structure with rows and columns. You can think of a 2D array as a table or matrix.
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] twoDArray = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing elements
int element = twoDArray[1][2];
System.out.println("Item[1][2]: " + element);
System.out.println("Array items:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(twoDArray[i][j] + " ");
}
System.out.println();
}
}
}