Java Arrays - Complete Guide + Questions
What is an Array in Java?
An array is a collection of elements of the same data type stored in a contiguous memory location.
1. Declaration and Initialization
a) Declaration
int[] marks;
String names[];
b) Initialization
int[] marks = new int[5];
marks[0] = 90;
marks[1] = 85;
Or inline:
int[] marks = {90, 85, 88, 92, 75};
2. Accessing and Traversing
for (int i = 0; i < marks.length; i++) {
System.out.println("Mark " + i + ": " + marks[i]);
For-each loop:
for (int mark : marks) {
System.out.println(mark);
}
3. Array Length
System.out.println("Length: " + marks.length);
4. Multidimensional Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
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();
5. Array Methods (java.util.Arrays)
import java.util.Arrays;
int[] nums = {5, 3, 9, 1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
int index = Arrays.binarySearch(nums, 3);
System.out.println("Index of 3: " + index);
6. Important Points
- Default values: int 0, boolean false, Object null
- Fixed size once declared
- Arrays are objects
- Passed by reference
Example Program:
public class ArrayDemo {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Mango"};
for (int i = 0; i < fruits.length; i++) {
System.out.println("Fruit " + i + ": " + fruits[i]);
Questions:
1. What is the default value of an int array in Java?
2. How do you access the last element of an array?
3. Write a program to reverse an array.
4. How is a 2D array stored in Java?
5. Whats the difference between .length and .length()?
6. Write code to find the maximum element in an array.
7. What is the output of Arrays.toString({3,2,1}) after sorting?