Bird
Raised Fist0
Javaprogramming~5 mins

Common array operations in Java

Choose your learning style10 modes available
Introduction

Arrays help us store many values in one place. Common operations let us add, find, or change these values easily.

You want to keep a list of student scores and find the highest score.
You need to check if a number exists in a list of phone numbers.
You want to change a specific item in a list, like updating a product price.
You want to add new items to a list and see all items.
You want to count how many times a value appears in a list.
Syntax
Java
public class ArrayOperations {
    private int[] array;
    private int size;

    public ArrayOperations(int capacity) {
        array = new int[capacity];
        size = 0;
    }

    public void add(int value) {
        if (size < array.length) {
            array[size] = value;
            size++;
        }
    }

    public int find(int value) {
        for (int i = 0; i < size; i++) {
            if (array[i] == value) {
                return i; // return index
            }
        }
        return -1; // not found
    }

    public void update(int index, int newValue) {
        if (index >= 0 && index < size) {
            array[index] = newValue;
        }
    }

    public void printAll() {
        for (int i = 0; i < size; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    public int countOccurrences(int value) {
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (array[i] == value) {
                count++;
            }
        }
        return count;
    }
}

This class uses a fixed-size array and a size variable to track how many items are added.

Indexing starts at 0, so the first element is at index 0.

Examples
Adds three numbers and prints: 10 20 30
Java
ArrayOperations arr = new ArrayOperations(5);
arr.add(10);
arr.add(20);
arr.add(30);
arr.printAll();
Prints nothing because array is empty (size is 0).
Java
ArrayOperations arr = new ArrayOperations(3);
arr.printAll();
Updates the first element from 5 to 15 and prints: 15
Java
ArrayOperations arr = new ArrayOperations(3);
arr.add(5);
arr.update(0, 15);
arr.printAll();
Counts how many times 7 appears and prints: 2
Java
ArrayOperations arr = new ArrayOperations(3);
arr.add(7);
arr.add(7);
arr.add(2);
int count = arr.countOccurrences(7);
System.out.println(count);
Sample Program

This program shows how to add numbers to the array, find an element's index, update a value, print all elements, and count occurrences of a value.

Java
public class Main {
    public static void main(String[] args) {
        ArrayOperations numbers = new ArrayOperations(5);

        System.out.println("Before adding elements:");
        numbers.printAll();

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(20);

        System.out.println("After adding elements:");
        numbers.printAll();

        int index = numbers.find(20);
        System.out.println("Index of 20: " + index);

        numbers.update(1, 25); // change 20 at index 1 to 25
        System.out.println("After updating index 1 to 25:");
        numbers.printAll();

        int count20 = numbers.countOccurrences(20);
        System.out.println("Count of 20: " + count20);
    }
}

class ArrayOperations {
    private int[] array;
    private int size;

    public ArrayOperations(int capacity) {
        array = new int[capacity];
        size = 0;
    }

    public void add(int value) {
        if (size < array.length) {
            array[size] = value;
            size++;
        }
    }

    public int find(int value) {
        for (int i = 0; i < size; i++) {
            if (array[i] == value) {
                return i;
            }
        }
        return -1;
    }

    public void update(int index, int newValue) {
        if (index >= 0 && index < size) {
            array[index] = newValue;
        }
    }

    public void printAll() {
        for (int i = 0; i < size; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
    }

    public int countOccurrences(int value) {
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (array[i] == value) {
                count++;
            }
        }
        return count;
    }
}
OutputSuccess
Important Notes

Adding an element takes O(1) time if space is available.

Finding an element takes O(n) time because it may check all elements.

Updating an element is O(1) because you access by index directly.

Counting occurrences is O(n) because it checks all elements.

Common mistake: Trying to add more elements than the array capacity causes no addition.

Use arrays when you know the maximum size and want fast access by index.

Summary

Arrays store multiple values in order and allow easy access by position.

Common operations include adding, finding, updating, printing, and counting values.

Understanding these helps manage lists of data simply and efficiently.

Practice

(1/5)
1. Which of the following correctly declares an array of integers with 5 elements in Java?
easy
A. int[] numbers = int[5];
B. int numbers = new int[5];
C. int numbers[] = new int;
D. int[] numbers = new int[5];

Solution

  1. Step 1: Understand Java array declaration syntax

    In Java, arrays are declared with the type followed by square brackets, then the variable name, and initialized with 'new' and size.
  2. Step 2: Check each option for correct syntax

    int[] numbers = new int[5]; uses correct syntax: int[] numbers = new int[5]; Options A, B, and D have syntax errors or missing parts.
  3. Final Answer:

    int[] numbers = new int[5]; -> Option D
  4. Quick Check:

    Correct array declaration = int[] numbers = new int[5]; [OK]
Hint: Remember: type[] name = new type[size]; for arrays [OK]
Common Mistakes:
  • Missing square brackets after type
  • Not using 'new' keyword
  • Incorrect variable initialization
2. Which of the following is the correct way to access the third element of an array named arr in Java?
easy
A. arr(3);
B. arr[2];
C. arr[3];
D. arr.get(2);

Solution

  1. Step 1: Recall Java array indexing

    Java arrays use zero-based indexing, so the first element is at index 0, second at 1, third at 2.
  2. Step 2: Identify correct syntax for accessing elements

    Elements are accessed with square brackets []. So arr[2] accesses the third element. Options A and D use incorrect syntax, and C accesses the fourth element.
  3. Final Answer:

    arr[2]; -> Option B
  4. Quick Check:

    Third element index = 2 [OK]
Hint: Arrays start at 0, so third element is arr[2] [OK]
Common Mistakes:
  • Using parentheses instead of brackets
  • Using 1-based indexing
  • Trying to use methods like get() on arrays
3. What is the output of the following Java code?
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < nums.length; i++) {
    sum += nums[i];
}
System.out.println(sum);
medium
A. 15
B. 10
C. 5
D. 0

Solution

  1. Step 1: Understand the array and loop

    The array nums contains 1, 2, 3, 4, 5. The loop runs from i=0 to i=4 (nums.length is 5).
  2. Step 2: Calculate the sum of all elements

    sum = 0 + 1 + 2 + 3 + 4 + 5 = 15.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Sum of 1 to 5 = 15 [OK]
Hint: Sum array by adding all elements in a loop [OK]
Common Mistakes:
  • Off-by-one error in loop
  • Starting sum at wrong value
  • Using wrong loop condition
4. The following code is intended to print all elements of the array data, but it causes a runtime error. What is the error?
int[] data = {10, 20, 30};
for (int i = 1; i <= data.length; i++) {
    System.out.println(data[i]);
}
medium
A. ArrayIndexOutOfBoundsException because loop goes beyond last index
B. Syntax error due to wrong for loop syntax
C. Prints all elements correctly
D. NullPointerException because array is not initialized

Solution

  1. Step 1: Analyze loop indices and array length

    The array has length 3, valid indices are 0, 1, 2. The loop runs i from 1 to 3 inclusive.
  2. Step 2: Identify index causing error

    When i = 3, data[3] is accessed, which is out of bounds and causes ArrayIndexOutOfBoundsException.
  3. Final Answer:

    ArrayIndexOutOfBoundsException because loop goes beyond last index -> Option A
  4. Quick Check:

    Loop index must be less than length [OK]
Hint: Loop indices must be 0 to length-1 for arrays [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Starting loop at 1 instead of 0
  • Ignoring zero-based indexing
5. Given an integer array arr, which code snippet correctly counts how many elements are greater than 10?
hard
A. int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 10) { count++; } } System.out.println(count);
B. int count = 0; for (int i = 1; i <= arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count);
C. int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count);
D. int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < 10) { count++; } } System.out.println(count);

Solution

  1. Step 1: Understand the counting condition

    We want to count elements strictly greater than 10, so condition is arr[i] > 10.
  2. Step 2: Check loop indices and condition correctness

    int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); uses correct zero-based indexing and correct condition. int count = 0; for (int i = 1; i <= arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); has out-of-bounds error. int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= 10) { count++; } } System.out.println(count); counts elements >= 10 (includes 10). int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] < 10) { count++; } } System.out.println(count); counts elements less than 10, which is wrong.
  3. Final Answer:

    int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] > 10) { count++; } } System.out.println(count); -> Option C
  4. Quick Check:

    Count elements with arr[i] > 10 using correct loop [OK]
Hint: Use i < arr.length and condition arr[i] > 10 to count [OK]
Common Mistakes:
  • Using <= instead of < in loop
  • Using wrong comparison operator
  • Starting loop at 1 causing index errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard