Skip to content
beginnerPhase 10 · Java Arrays & Strings

Arrays in Java

Declare, initialize, traverse, and manipulate arrays in Java.

1h
5 problems
Topic Progress0%

Array Declaration

Array Declaration in Java

In Java, arrays are objects that hold a fixed number of elements of a single type. Unlike arrays in C or C++, Java arrays are first-class objects with a length property and inherit from Object.

Syntax

// Declare an array variable
int[] numbers;      // Preferred style
int numbers2[];     // Also valid (C-style, not recommended)

// The declaration does NOT create the array
// numbers = null at this point

Creating Arrays

// Using new keyword - creates array with default values
int[] scores = new int[5];           // [0, 0, 0, 0, 0]
String[] names = new String[3];      // [null, null, null]
double[] prices = new double[4];     // [0.0, 0.0, 0.0, 0.0]

// Default values by type:
// int, long, short, byte → 0
// float, double → 0.0
// char → '\u0000'
// boolean → false
// Object references → null

Array Size

int[] arr = new int[10];
int length = arr.length;  // 10 (not a method call, it's a field)

// Arrays are FIXED size after creation
// You cannot add or remove elements
// To 'resize', you must create a new array

Multiple Declaration

// Declare multiple arrays
int[] a, b;  // a and b are both int arrays

// Be careful with this:
int c[], d;  // c is int array, d is just int!

Key Points

  1. Array size must be non-negative
  2. Array size is determined at runtime (not compile-time constant)
  3. Array index starts at 0
  4. Accessing invalid index throws ArrayIndexOutOfBoundsException
  5. Arrays know their own length via .length field

Array Initialization

Array Initialization Methods

Java provides multiple ways to initialize arrays with values.

Static Initialization

// Short form - compiler infers size
int[] primes = {2, 3, 5, 7, 11, 13};
String[] fruits = {"apple", "banana", "cherry"};

// Long form
int[] primes2 = new int[]{2, 3, 5, 7, 11, 13};

// Note: You cannot specify size with static initialization
// int[] arr = new int[3]{1, 2, 3};  // COMPILE ERROR!

Dynamic Initialization

// Create array and set values separately
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Or use a loop
int[] squares = new int[10];
for (int i = 0; i < squares.length; i++) {
    squares[i] = i * i;
}

Array Copy

// Method 1: System.arraycopy()
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[5];
System.arraycopy(src, 0, dest, 0, src.length);

// Method 2: Arrays.copyOf()
int[] copy = Arrays.copyOf(src, src.length);

// Method 3: clone()
int[] cloned = src.clone();

// Method 4: Manual copy
int[] manual = new int[src.length];
for (int i = 0; i < src.length; i++) {
    manual[i] = src[i];
}

Array with Variable Size

// Size determined at runtime
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] dynamicArray = new int[n];

// This is still a fixed-size array!
// Once created, cannot change size

Anonymous Arrays

// Create and pass array in one line
printArray(new int[]{1, 2, 3, 4, 5});
printArray(new String[]{"hello", "world"});

static void printArray(int[] arr) {
    for (int num : arr) {
        System.out.print(num + " ");
    }
}

Array Traversal

Array Traversal Techniques

Traversing (iterating through) arrays is one of the most fundamental operations.

Traditional For Loop

int[] arr = {10, 20, 30, 40, 50};

// Forward traversal
for (int i = 0; i < arr.length; i++) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}

// Backward traversal
for (int i = arr.length - 1; i >= 0; i--) {
    System.out.println("Element at index " + i + ": " + arr[i]);
}

Enhanced For Loop (For-Each)

int[] arr = {10, 20, 30, 40, 50};

// Enhanced for loop - simpler syntax
for (int num : arr) {
    System.out.println(num);
}

// Limitations:
// - Cannot access index
// - Cannot modify array elements
// - Cannot iterate backwards

While Loop

int[] arr = {10, 20, 30, 40, 50};
int i = 0;

while (i < arr.length) {
    System.out.println(arr[i]);
    i++;
}

Using Arrays.toString()

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

// Quick way to print entire array
System.out.println(Arrays.toString(arr));
// Output: [1, 2, 3, 4, 5]

Practical Examples

// Find maximum element
int[] arr = {5, 2, 9, 1, 7};
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
    if (arr[i] > max) {
        max = arr[i];
    }
}
System.out.println("Maximum: " + max);  // 9

// Reverse array in place
int[] arr = {1, 2, 3, 4, 5};
int left = 0, right = arr.length - 1;
while (left < right) {
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;
    left++;
    right--;
}
// arr is now {5, 4, 3, 2, 1}

Time Complexity

  • All traversal methods: O(n)
  • No difference in performance between loop types

Utility Methods

java.util.Arrays Utility Class

The Arrays class provides static methods to work with arrays.

Sorting

import java.util.Arrays;

int[] arr = {5, 2, 8, 1, 9};
Arrays.sort(arr);  // [1, 2, 5, 8, 9]

// Sorting with custom order
Integer[] nums = {5, 2, 8, 1, 9};
Arrays.sort(nums, Collections.reverseOrder());  // [9, 8, 5, 2, 1]

// Sorting part of array
int[] arr2 = {5, 2, 8, 1, 9, 3};
Arrays.sort(arr2, 1, 4);  // Sort index 1 to 3: [5, 1, 2, 8, 9, 3]

Searching (Binary Search)

int[] arr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(arr, 3);  // 2 (found)
int index2 = Arrays.binarySearch(arr, 6);  // -4 (not found, insertion point)

// Must be sorted before searching!

Copying

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

// Copy with same size
int[] copy1 = Arrays.copyOf(src, src.length);  // [1, 2, 3, 4, 5]

// Copy with new size (larger or smaller)
int[] copy2 = Arrays.copyOf(src, 3);   // [1, 2, 3]
int[] copy3 = Arrays.copyOf(src, 7);   // [1, 2, 3, 4, 5, 0, 0]

// Copy range
int[] copy4 = Arrays.copyOfRange(src, 1, 4);  // [2, 3, 4]

Filling

int[] arr = new int[5];
Arrays.fill(arr, 10);  // [10, 10, 10, 10, 10]

// Fill range
int[] arr2 = new int[5];
Arrays.fill(arr2, 2, 4, 100);  // [0, 0, 100, 100, 0]

Comparison

int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = {1, 2, 4};

Arrays.equals(a, b);  // true
Arrays.equals(a, c);  // false

// For multi-dimensional arrays
int[][] x = {{1, 2}, {3, 4}};
int[][] y = {{1, 2}, {3, 4}};
Arrays.deepEquals(x, y);  // true

Converting to String

int[] arr = {1, 2, 3, 4, 5};
String str = Arrays.toString(arr);  // "[1, 2, 3, 4, 5]"

// For multi-dimensional
int[][] arr2 = {{1, 2}, {3, 4}};
String str2 = Arrays.deepToString(arr2);  // "[[1, 2], [3, 4]]"

Converting to List

// For object arrays
Integer[] nums = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.asList(nums);  // Fixed-size list
List<Integer> mutableList = new ArrayList<>(Arrays.asList(nums));

// For primitive arrays - no direct method
int[] primitives = {1, 2, 3};
List<Integer> list2 = Arrays.stream(primitives)
                            .boxed()
                            .collect(Collectors.toList());

Time Complexity

Array Operations Time Complexity

Understanding the performance characteristics of array operations is crucial for interviews.

Operation Complexities

Operation Time Space Notes
Access by index O(1) O(1) Direct memory calculation
Search (unsorted) O(n) O(1) Must check each element
Search (sorted) O(log n) O(1) Binary search possible
Insert at end O(1)* O(1) *If space available
Insert at beginning O(n) O(n) Must shift all elements
Insert at middle O(n) O(n) Must shift half elements
Delete at end O(1) O(1) Just decrease size
Delete at beginning O(n) O(n) Must shift all elements
Delete at middle O(n) O(n) Must shift elements

Why O(1) Access?

// Memory address calculation:
// address = base_address + (index * element_size)

int[] arr = new int[5];
// Base address: 1000
// Element size: 4 bytes (int)

// arr[3] = 1000 + (3 * 4) = 1012
// Direct calculation, no traversal needed!

Why O(n) Insertion/Deletion?

// Insert 99 at index 2
int[] arr = {1, 2, 3, 4, 5};
// Step 1: Shift elements right
// [1, 2, _, 3, 4, 5]  ← shift 3, 4, 5
// Step 2: Insert
// [1, 2, 99, 3, 4, 5]

// Deletion at index 2
int[] arr = {1, 2, 99, 3, 4, 5};
// Step 1: Remove element
// [1, 2, _, 3, 4, 5]
// Step 2: Shift elements left
// [1, 2, 3, 4, 5]

When to Use Arrays

Good for:

  • When you know the exact number of elements
  • When you need fast random access
  • When memory is a concern (arrays are more compact)
  • When working with primitive types (no boxing overhead)

Bad for:

  • When you need to add/remove elements frequently
  • When you don't know the size in advance
  • When you need advanced operations like sorting by custom criteria

Common Interview Patterns

// Pattern 1: Two-pointer (for sorted arrays)
// Pattern 2: Sliding window (for subarray problems)
// Pattern 3: Prefix sum (for range queries)
// Pattern 4: Sorting first (when order doesn't matter)
// Pattern 5: HashMap (for frequency/counting)

Practice Problems

0/5solved
Two Sum
HashMap

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Example:

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1]

nums[0] + nums[1] = 2 + 7 = 9

Optimal Solution — O(n) time, O(n) space

Use HashMap to store seen numbers and their indices. For each number, check if target - num exists in map.

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[]{map.get(complement), i};
        }
        map.put(nums[i], i);
    }
    return new int[]{};
}

Edge Cases:

  • Same element used twice
  • Negative numbers
  • Single pair only
Best Time to Buy and Sell Stock
Single Pass

Given prices array, find maximum profit from buying and selling once.

Example:

Input: prices = [7, 1, 5, 3, 6, 4]

Output: 5

Buy at 1, sell at 6

Optimal Solution — O(n) time, O(1) space

Track minimum price seen so far, calculate profit at each step.

public int maxProfit(int[] prices) {
    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;
    for (int price : prices) {
        minPrice = Math.min(minPrice, price);
        maxProfit = Math.max(maxProfit, price - minPrice);
    }
    return maxProfit;
}

Edge Cases:

  • Prices always decreasing
  • Single price
  • All same prices
Maximum Subarray
Kadane's Algorithm

Find contiguous subarray with largest sum.

Example:

Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Output: 6

Subarray [4, -1, 2, 1] has sum 6

Optimal Solution — O(n) time, O(1) space

Kadane's algorithm - track current sum, reset when negative.

public int maxSubArray(int[] nums) {
    int maxSum = nums[0];
    int currentSum = nums[0];
    for (int i = 1; i < nums.length; i++) {
        currentSum = Math.max(nums[i], currentSum + nums[i]);
        maxSum = Math.max(maxSum, currentSum);
    }
    return maxSum;
}

Edge Cases:

  • All negative numbers
  • Single element
  • All positive
Merge Sorted Arrays
Two Pointers

Merge two sorted arrays into one sorted array.

Example:

Input: nums1 = [1, 2, 3], nums2 = [2, 5, 6]

Output: [1, 2, 2, 3, 5, 6]

Merged and sorted

Optimal Solution — O(n + m) time, O(n + m) space

Use two pointers, compare and add smaller element to result.

public int[] merge(int[] nums1, int[] nums2) {
    int[] result = new int[nums1.length + nums2.length];
    int i = 0, j = 0, k = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] <= nums2[j]) {
            result[k++] = nums1[i++];
        } else {
            result[k++] = nums2[j++];
        }
    }
    while (i < nums1.length) result[k++] = nums1[i++];
    while (j < nums2.length) result[k++] = nums2[j++];
    return result;
}

Edge Cases:

  • One empty array
  • Both empty
  • No common elements
Contains Duplicate
HashSet

Given integer array, return true if any value appears at least twice.

Example:

Input: nums = [1, 2, 3, 1]

Output: true

1 appears twice

Optimal Solution — O(n) time, O(n) space

Use HashSet to track seen elements.

public boolean containsDuplicate(int[] nums) {
    Set<Integer> seen = new HashSet<>();
    for (int num : nums) {
        if (seen.contains(num)) return true;
        seen.add(num);
    }
    return false;
}

Edge Cases:

  • Single element
  • All duplicates
  • Empty array

Quiz

1. What is the default value of elements in a newly created int array?

Question 1 options

2. Which method is used to sort an array in ascending order?

Question 2 options

3. What happens when you access an invalid array index?

Question 3 options

4. What is the time complexity of accessing an array element by index?

Question 4 options

Flashcards

Question

What is the difference between int[] arr = new int[3] and int[] arr = {1,2,3}?

Answer

new int[3] creates array with default values (0). {1,2,3} is static initialization with explicit values.

Question

How do you get the length of an array in Java?

Answer

arr.length (it's a field, not a method - no parentheses)

Question

Can you resize an array after creation?

Answer

No. Arrays are fixed-size. To 'resize', create a new array and copy elements.

Question

What is the time complexity of searching in a sorted vs unsorted array?

Answer

Sorted: O(log n) with binary search. Unsorted: O(n) with linear search.

Question

What is Arrays in Java?

Answer

Arrays in Java is a key concept in Java programming.

Revision Notes

Key Takeaways

  • 1.Arrays are fixed-size, zero-indexed, contiguous memory
  • 2.Access is O(1), insertion/deletion is O(n)
  • 3.Use Arrays utility class for common operations
  • 4.Consider ArrayList for dynamic sizing

Interview Tips

  • Always check for null and empty arrays
  • Consider edge cases: single element, all same elements
  • Know when to use arrays vs ArrayList
  • Practice common patterns: two-pointer, sliding window, HashMap

Cheat Sheet

Cheat Sheet

  • Declaration: int[] arr;
  • Initialization: int[] arr = new int[5]; or int[] arr = {1,2,3};
  • Length: arr.length
  • Access: arr[i]
  • Sort: Arrays.sort(arr)
  • Search: Arrays.binarySearch(arr, key)
  • Copy: Arrays.copyOf(arr, len)
  • Fill: Arrays.fill(arr, val)
  • Compare: Arrays.equals(a, b)
  • Print: Arrays.toString(arr)