-3

When trying to run the following code:

public static void main(String[] args) {
    int num_amount = 7;
    int[] num_array = {3, 4, 1, 1, 2, 12, 1};
    System.out.println(num_array.length);
    for (int i = 0; i < num_array.length; i++) {
        num_array[i] = 0;
        System.out.println(num_array);
    }
}

This is the output i get:

7
[I@ea30797
[I@ea30797
[I@ea30797
[I@ea30797
[I@ea30797
[I@ea30797
[I@ea30797

Has anyone ever experienced this "unusual" result? If so, what solution did you try out? Thanks in advance.

ppsn
  • 39
  • 5
  • 3
    Yes, everybody has experience this. It is the default 'toString' of a java array. – matt Mar 15 '22 at 15:06
  • 1
    `System.out.println(num_array);` -> `System.out.println(num_array[i]);` – paladin Mar 15 '22 at 15:07
  • You are printing the array's reference (which is always the same because it's always the same array). You are changing the values in the array, not the array itself – Bentaye Mar 15 '22 at 15:12

3 Answers3

2

If you want to print the contents of an array you can use Arrays.toString.

System.out.println(Arrays.toString(num_array));
Anton Belev
  • 11,963
  • 22
  • 70
  • 111
1

In Java, you do not print an array by placing the array name inside System.out.println();.

Here, you should use System.out.println(Arrays.toString(num_array));

See here for how to print an array in Java: https://stackoverflow.com/a/409795/18449247 (you should use .toString here)

Nathan W
  • 11
  • 3
0

You can try

System.out.println(num_array[i]);

If you want to print each element in new line..

Prashant
  • 48
  • 4
  • No, it's obvious from the code that the OP wanted to print the _entire_ array each time through the loop and see it changing one element at a time. – k314159 Mar 15 '22 at 15:15