Java Arrays Cheat Sheet

Array Basics



Array Declaration


Java
Copy
int[] intArray;       // Declares an array of integers

String[] strArray;    // Declares an array of strings

Array Initialization


Java
Copy
intArray = new int[5];  // Creates an array of 5 integers with default values (0)

strArray = new String[5]; // Creates an array of 5 strings with default values (null)

Array Declaration & Initialization Combined


Java
Copy
int[] intArray = new int[5];

String[] strArray = new String[5];

Array Literal Initialization


Java
Copy
int[] intArray = {1, 2, 3, 4, 5};  // Array with values 1, 2, 3, 4, 5

String[] strArray = {"One", "Two", "Three"}; // Array with values "One", "Two", "Three"

Array Access and Modification



Accessing Array Elements


Java
Copy
int firstElement = intArray[0];  // Access the first element

String secondElement = strArray[1]; // Access the second element

Modifying Array Elements


Java
Copy
intArray[0] = 10;  // Sets the first element to 10

strArray[1] = "Two Updated"; // Sets the second element to "Two Updated"

Iterating Through Arrays



Using for loop


Java
Copy
String[] fruits = {"Apple", "Orange", "Grapes", "Mango"};

int length = fruits.length;  // Gets the length of the array

for (int i = 0; i < length; i++)
{
	System.out.println(fruits[i]);
}

Using Enhanced for Loop (For-Each Loop)


Java
Copy
String[] fruits = {"Apple", "Orange", "Grapes", "Mango"};

for (String fruit : fruits)
{
	System.out.println(fruit);
}

Multidimensional Arrays



Java
Copy
int[][] arr1 = new int[2][2]; // 2 row and 2 column

arr1[0][0] = 1;
arr1[0][1] = 2;
arr1[1][0] = 3;
arr1[1][1] = 4;

for (int i = 0; i < arr1.length; i++)
{
	for (int j = 0; j < arr1[i].length; j++)
	{
		System.out.print(arr1[i][j] + " "); // 1 2 3 4
	}
}

System.out.println();

int[][] arr2 = {{1, 2, 3}, {2, 4, 5}, {4, 4, 5}};

for (int i = 0; i < 3; i++)
{
	for (int j = 0; j < 3; j++)
	{
		System.out.print(arr2[i][j] + " "); // 1 2 3 2 4 5 4 4 5
	}
}

Creating Jagged Arrays (Arrays with Varying Lengths)


Java
Copy
int[][] jaggedArray = new int[3][];

jaggedArray[0] = new int[5];

jaggedArray[1] = new int[3];

jaggedArray[2] = new int[4];

Arrays in Method Parameters


Java
Copy
public static void modifyArray(int[] array) {
    array[0] = 100;  // Modifies the first element of the array
}

Returning Arrays from Methods


Java
Copy
public static int[] createArray() {
    return new int[]{1, 2, 3, 4, 5};
}

Common Array Operations



Java
Copy
// Copying Arrays

// Following code copies entire array
int[] newArray = Arrays.copyOf(intArray, intArray.length); 

// Following code copies elements from index 1 to 3
int[] partialArray = Arrays.copyOfRange(intArray, 1, 4); 

// Filling Arrays

// Following code fills the entire array with 10
Arrays.fill(intArray, 10); 

// Sorting Arrays

// Following code sorts the array in ascending order
Arrays.sort(intArray);

// Searching Arrays

// Following code searches for element 3, returns its index
int index = Arrays.binarySearch(intArray, 3);

// Comparing Arrays

// Following code compares two arrays for equality
boolean isEqual = Arrays.equals(intArray, newArray); 

// Converting Array to String

// Following code converts array to a string representation
String arrayString = Arrays.toString(intArray);

Advanced Array Operations



Java
Copy
// Cloning Arrays

// Following code creates a shallow copy of the array
int[] clonedArray = intArray.clone();

// Array to List Conversion

// Following code converts array to a fixed-size list
List<String> strList = Arrays.asList(strArray);

// List to Array Conversion

// Following code converts list back to array
String[] newArray = strList.toArray(new String[0]);

Immutable Arrays Returned by asList()


Arrays.asList() returns a fixed-size list backed by the array, so you cannot add or remove elements from the list, though you can modify existing elements.

Working with Arrays of Objects



Declaring and Initializing

Java
Copy
class Student {
    String name;
    int age;
    
    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Array of 3 Student objects
Student[] students = new Student[3];

// Assigning Student objects to the array
students[0] = new Student("Alice", 20);

students[1] = new Student("Bob", 22);

students[2] = new Student("Charlie", 19);

Accessing and Modifying Object Arrays


Java
Copy
// Accessing the name of the first student
String studentName = students[0].name;

// Modifying the age of the second student
students[1].age = 23;

Iterating Through Object Arrays


Java
Copy
for (Student student : students) {
    System.out.println(student.name + " is " + student.age + " years old.");
}

Arrays with Stream API (Java 8+)



Java
Copy
// Convert Array to Stream

// Following code creates a stream from an int array
IntStream intStream = Arrays.stream(intArray);

// Following code creates a stream from a String array
Stream<String> strStream = Arrays.stream(strArray);

// Filtering an Array Using Streams

// Following code filters even numbers
int[] evenNumbers = Arrays.stream(intArray).filter(x -> x % 2 == 0).toArray(); 

// Mapping and Collecting Stream Results

// Following code squares each element
int[] squaredNumbers = Arrays.stream(intArray).map(x -> x * x).toArray();

// Reducing an Array to a Single Value

Following code sums all elements in the array
int sum = Arrays.stream(intArray).reduce(0, (a, b) -> a + b);

Varargs (Variable-Length Arguments)



Using Varargs in Methods


Java
Copy
public static void printNumbers(int... numbers) {
    for (int number : numbers) {
        System.out.println(number);
    }
}

// Calls method with multiple arguments
printNumbers(1, 2, 3, 4, 5);

Varargs and Overloading



Java
Copy
public static void printNumbers(int[] numbers) {
    for (int number : numbers) {
        System.out.println(number);
    }
}

// Calls method with array as argument
printNumbers(new int[]{1, 2, 3, 4, 5});

Common Arrays Exception



ArrayIndexOutOfBoundsException


Accessing an array with an invalid index (either negative or beyond the array size) will throw ArrayIndexOutOfBoundsException.

NullPointerException


Declaring an array does not allocate memory for its elements. Accessing elements in an uninitialized object array will throw NullPointerException.