Arrays can be created with values directly or with a fixed size. Access elements using square brackets and a zero-based index.
public class ArrayBasics {
public static void main(String[] args) {
int[] marks = {85, 90, 76};
System.out.println(marks[0]);
marks[1] = 95;
System.out.println("Length: " + marks.length);
}
}
Use a normal for loop when you need the index. Use enhanced for when you only need values.
public class ArrayTraversal {
public static void main(String[] args) {
String[] names = {"Asha", "Ravi", "Meera"};
for (int i = 0; i < names.length; i++) {
System.out.println(i + ": " + names[i]);
}
for (String name : names) {
System.out.println(name.toUpperCase());
}
}
}
The Arrays utility class provides helper methods for sorting, searching, copying, comparing, and printing arrays.
import java.util.Arrays;
public class ArraysUtilityDemo {
public static void main(String[] args) {
int[] numbers = {5, 1, 9, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.binarySearch(numbers, 9));
int[] copy = Arrays.copyOf(numbers, numbers.length);
System.out.println(Arrays.equals(numbers, copy));
}
}
A 2D array is an array of arrays. Rows can have equal length like a matrix, or different lengths like a jagged table.
public class MatrixDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
Indexes start at zero, so an array of length n ends at n - 1.
No. Use ArrayList when the number of elements must change.
It creates a new array and copies as many elements as fit.
Practice, interview questions, and compiler links for Core Java.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.