Why does my Java array print the last value in all positions after a loop assignment?
21:32 25 May 2026

I'm learning Java and trying to store user input values into an array using a loop, but when I print the array, all positions show the same value (the last one entered). I cannot figure out why the previous values are being overwritten.

Here is my code:


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] numbers = new int[5];
        int temp = 0;

        for (int i = 0; i < 5; i++) {
            System.out.print("Enter a number: ");
            temp = sc.nextInt();
        }

        for (int i = 0; i < 5; i++) {
            numbers[i] = temp;
        }

        for (int i = 0; i < 5; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }
    }
}

If I enter 1, 2, 3, 4, 5, the observed output is:

numbers[0] = 5
numbers[1] = 5
numbers[2] = 5
numbers[3] = 5
numbers[4] = 5

But I expected:

numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
numbers[3] = 4
numbers[4] = 5

What I already tried:

- I printed temp inside the first loop and the input is correct there.

- I changed int[] numbers to int numbers[] but got the same result.

- I searched for Java array stores same value but only found ArrayList answers.

Any help understanding why this happens would be appreciated!

javascript java arrays loops swing