0

I am trying to write a simple program using the code below to make a single dimensional array that you can then call a value from using the index numbers. I am using and as my compiler. Whenever I try to debug or run the program, the full array prints out as this: [I@1fa8d3b.

class Array    
{
public static void main(String[] args)
{
    int[] MyArray = new int[] {15, 45, 34, 78, 65, 47, 90, 32, 54, 10};
    System.out.println("The full array is:");
    System.out.println(MyArray);
    System.out.println("The 4th entry in the data is: " + MyArray[3]);
}
}

The correct data entry prints out when it is called though. I have tried to look for answers online as to what I should do, but I could not find anything that actually works. I am just starting to learn Java so there could be a very simple answer to this that I am just overlooking. If anyone has any ideas, I would be greatly appreciative.

Bananeweizen
  • 21,797
  • 8
  • 68
  • 88
user2320169
  • 31
  • 1
  • 1
  • 1

4 Answers4

8

Java is an object oriented language. When you are calling System.out.print(MyArray); in Java you are actually printing the address of the object on the heap in memory the toString code from it's parent class Object, the code is shown below contributed by the comment from EngFouad, sorry for misspeaking. The weird String you see printed out is the reference the computer uses to find your data when you ask for something associated with the variable MyArray.

As stated by the other answers, to print out the data of your object you can use the Array class's built in .toString() method. This will print the data from the object instead of just the object reference.

System.out.println(Arrays.toString(MyArray);

Correction Actually it is toString() of the class Object: getClass().getName() + "@" + Integer.toHexString(hashCode()). – Eng.Fouad

Mistake above was corrected thanks for the comments, hate to give the wrong information. I misunderstood it myself. Here is the API reference to see the code:

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()

Kyle
  • 14,036
  • 11
  • 46
  • 61
3

Use:

System.out.println(Arrays.toString(MyArray));

In order to print the array elements. In your case you used the default Object.toString() implementation, which is not so informative...

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
2

Use this instead:

System.out.println(Arrays.toString(MyArray));

API Reference: Arrays.toString(int[])

durron597
  • 31,968
  • 17
  • 99
  • 158
0

to print the array you need to use the loop. for example:

for (int i: MyArray){
System.out.print(i + " ")}
Nikitin Mikhail
  • 2,983
  • 9
  • 42
  • 67