0

I'm new to Java and is trying to learn the concept of constructor. I tried to print out the value of arrayOfInts in the main method using (to test whether the constructor was initialised the way I expected)

System.out.println(ds.arrayOfInts);

However, instead of printing out the values, the output is:

[I@15db9742

Why am I getting the wrong result and how I can print out the correct result? (i.e. the value stored in arrayOfInts).

 public class DataStructure {

    public static void main(String[] args) {
        DataStructure ds = new DataStructure();
        //System.out.println(ds.arrayOfInts); Doesnt work as expected

    }

    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        int arrayValue = 0;
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = ++arrayValue;
        }
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

2

You are trying to print an array. An array is an object.

In order to display it correctly, you can loop through it, or use the Arrays.toString() method:

System.out.println(Arrays.toString(ds.arrayOfInts));

which returns a string representation of the specified array.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
1

Arrays are objects in java. You need to iterate over elements and print them. Here is a sample implementation using the for-each loop.

 public void print() {
   for (int x : arrayOfInts) {
     System.out.println(x);
   }
 }
YoungHobbit
  • 13,254
  • 9
  • 50
  • 73