Why Does This for-loop Not Update My Array?

Profile Picture

Henrique Sa

OP
Admin
@riquelds.bsky.social
3 days ago

This code is supposed to replace negative numbers with 0, but it doesn’t change anything. What’s wrong with it?

int[] nums = {-1, 5, -3, 7};

for (int n : nums) {
    if (n < 0) {
        n = 0;
    }
}
System.out.println(Arrays.toString(nums)); // Still prints negatives
java oop error-handling