Manipulating Array Elements Inside a For Loop in Java


Suppose you have an array nums and your task is to increment every number in that array by one.

The first idea that might come to your mind is to write a for loop like this:

int[] nums = {1, 2, 3};

// Increment items:
for (int num : nums) {
  num++;
}

// Print the array after:
for (int num : nums) {
  System.out.println(num);
}

but when you run this code, you'll be surprised to see that the output is:

1
2
3

No element in nums changed its value. How is this possible since we clearly do num++ for every num in nums?


Let's talk about copies:

Take a look at this code:

int number = 100;

int number_copy = number;

number_copy++;

System.out.println(number_copy); // Output: 101
System.out.println(number); // Output: 100

Although we wrote int number_copy = number;, this doesn't mean that number and number_copy are one and the same.

number_copy is a completely different entity (stored at a different memory address) than number.

What we did is initialize this new number_copy entity with the value of number. That's why we say the number_copy is a copy of number.

And so number_copy++ will only increment number_copy and won't have any effect on number.


The loop variable is just a copy:

This is what also happens with a for loop.

Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.

This code

int[] nums = {1, 2, 3};

for (int num : nums) {
  num++;
}

works exactly like this code:

int[] nums = {1, 2, 3};

int num = nums[0];
num++;

num = nums[1];
num++;

num = nums[2];
num++;

Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.

You'll see this better if we also print the value of num on each iteration.

int[] nums = {1, 2, 3};

for (int num : nums) {
  num++;
  System.out.println(num);
}

// Print the array after:
for (int num : nums) {
  System.out.println(num);
}

The output of this code is:

2
3
4
1
2
3

Looping over the indices:

In order to manipulate the entries of some array we have to loop over the items' indices:

int[] nums = {1, 2, 3};

for (int index = 0; index < nums.length; index++) {
  nums[index]++;
}

This code works exactly like this one:

int[] nums = {1, 2, 3};

int index = 0;
nums[index]++;

index++;
nums[index]++;

index++;
nums[index]++;

In this way we directly manipulate the actual entries of the list (nums[0], nums[1], etc.)

Assignment:

Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.

Introduction

In this lesson, we will explore how to manipulate array elements inside a for loop in Java. This is a fundamental concept in programming that is crucial for tasks such as data processing, algorithm implementation, and more. Understanding how to correctly modify array elements is essential for writing efficient and bug-free code.

Understanding the Basics

Arrays in Java are used to store multiple values in a single variable. When you want to perform operations on each element of an array, you typically use a for loop. However, it's important to understand that the loop variable in a for-each loop is a copy of the array element, not the element itself. This means that modifying the loop variable does not change the original array.

For example:

int[] nums = {1, 2, 3};

for (int num : nums) {
  num++;
}

for (int num : nums) {
  System.out.println(num);
}

The output will be:

1
2
3

This happens because num is a copy of each element in nums, so incrementing num does not affect the original array.

Main Concepts

To correctly manipulate the elements of an array, you need to loop over the indices of the array and modify the elements directly. This can be done using a traditional for loop:

int[] nums = {1, 2, 3};

for (int index = 0; index < nums.length; index++) {
  nums[index]++;
}

In this way, you are directly accessing and modifying the elements of the array.

Examples and Use Cases

Let's look at an example where we need to increment even numbers and decrement odd numbers in an array:

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

for (int index = 0; index < nums.length; index++) {
  if (nums[index] % 2 == 0) {
    nums[index]++;
  } else {
    nums[index]--;
  }
}

for (int num : nums) {
  System.out.println(num);
}

The output will be:

0
3
2
5
4

This demonstrates how to conditionally modify array elements based on their values.

Common Pitfalls and Best Practices

One common mistake is to use a for-each loop when you need to modify the elements of an array. Always use a traditional for loop when you need to change the values of the array elements. Additionally, ensure that your loop indices are within the bounds of the array to avoid ArrayIndexOutOfBoundsException.

Advanced Techniques

For more advanced manipulation, you can use nested loops, lambda expressions, or streams (introduced in Java 8). For example, using streams to increment even numbers and decrement odd numbers:

import java.util.Arrays;

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

nums = Arrays.stream(nums)
             .map(num -> num % 2 == 0 ? num + 1 : num - 1)
             .toArray();

for (int num : nums) {
  System.out.println(num);
}

Code Implementation

Here is the complete code to increment even numbers and decrement odd numbers in an array:

public class Main {
  public static void main(String[] args) {
    int[] nums = {1, 2, 3, 4, 5};

    // Loop through the array and modify elements
    for (int index = 0; index < nums.length; index++) {
      if (nums[index] % 2 == 0) {
        nums[index]++;
      } else {
        nums[index]--;
      }
    }

    // Print the modified array
    for (int num : nums) {
      System.out.println(num);
    }
  }
}

Debugging and Testing

When debugging, use print statements to check the values of array elements at different stages of your loop. For testing, write test cases that cover various scenarios, such as arrays with all even numbers, all odd numbers, and a mix of both.

public class MainTest {
  public static void main(String[] args) {
    testArrayManipulation(new int[]{1, 2, 3, 4, 5}, new int[]{0, 3, 2, 5, 4});
    testArrayManipulation(new int[]{2, 4, 6}, new int[]{3, 5, 7});
    testArrayManipulation(new int[]{1, 3, 5}, new int[]{0, 2, 4});
  }

  public static void testArrayManipulation(int[] input, int[] expected) {
    Main.main(input);
    assert Arrays.equals(input, expected) : "Test failed for input: " + Arrays.toString(input);
  }
}

Thinking and Problem-Solving Tips

When approaching problems related to array manipulation, break down the problem into smaller steps. First, identify the operation you need to perform on each element. Then, decide whether you need to use a for-each loop or a traditional for loop. Finally, implement and test your solution incrementally.

Conclusion

Manipulating array elements inside a for loop is a fundamental skill in Java programming. By understanding the difference between for-each loops and traditional for loops, you can avoid common pitfalls and write efficient code. Practice with different scenarios to master this concept.

Additional Resources