-3

I am trying to print an array and I think I got all the codes correct, don't known why I am getting the result below... my code is

public class App {

    public static void main(String[] args) {
        int[] array = new int[8];

        for (int i = 0; i< array.length; i++){
            array[i] = i;
            System.out.print("| " + array + " ");
        }

        System.out.println(" ");
    }
}   

but i am printing result like below, why?

| [I@15db9742 | [I@15db9742 | [I@15db9742 | [I@15db9742 | [I@15db9742 | [I@15db9742 | [I@15db9742 | [I@15db9742

jakubbialkowski
  • 1,546
  • 16
  • 24
Kingsfull123
  • 483
  • 1
  • 6
  • 12

3 Answers3

6

It's because

System.out.print("| " + array + " ");

is shorthand for

System.out.print("| " + array.toString() + " ");

and the toString() method doesn't print the individual elements (if it did then all hell could be let loose for large arrays, so the clever Java bods decided to delegate that to Arrays.toString(array)).

What you need in this case is

System.out.print("| " + array[i] + " ");

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Even if `array.toString()` printed out every element, the original code still wouldn't behave as intended. It would repeatedly print out the entire array, rather than once. – Kevin Feb 01 '17 at 13:20
0

You are getting the @15db9742, that is the hashcode of the array object.

try with:

for (int i = 0; i< array.length; i++){
    array[i] = i;
    System.out.print("| " + array[i]+ " ");
}

or printing all at once

Arrays.toString(array)
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

It's printing exactly what you have instructed it to do so, what output are you expecting?

What values are in the original Array etc?

Try printing the chosen array item instead of the whole array.

public static void main(String[] args) { int[] array = new int[8];

for (int i = 0; i< array.length; i++){
var item = array[i];
System.out.print("| " + item + " ");
}
System.out.println(" ");
DaveOz
  • 98
  • 11