This question already has an answer here:
-
How do I print my Java object without getting “SomeType@2f92e0f4”?
10 answers
Consider a simple case like this one :
public static void array()
{
String myString = "STACKOVERFLOW";
int [] checkVal = new int[myString.length()];
for(int i=0; i<myString.length();i++){
checkVal[i] = (int)myString.charAt(i);
}
System.out.println(checkVal[0]);
System.out.println(checkVal[1]);
System.out.println(checkVal[2]);
System.out.println(checkVal[3]);
System.out.println(checkVal[4]);
System.out.println(checkVal);
}
This will output the following :
83
84
65
67
75
[I@fc9944
Can some one please explain this to me ? How can I retrieve the proper information from the Array instead of it's memory allocation ?
If you want it pretty printed, use Arrays.toString
to do it:
System.out.println(Arrays.toString(checkVal);
If not, it will just print out the toString
of the array, which is inherited from Object
, and generated a String
contains its type and the hash code:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
This answer also has relevant info.
after checkVal[4] you reference checkVal without an index []. this seems to correspond to your garbage line. if you are trying to get all values to print in the final System.out, seems you could do a loop through the array and keep apending the values to a string with a space in between numbers, and then print that string.
When you try to print any object's value, its toString() method is called(inherited from Object class). If the class does not override this method then super class implementation of this method is invoked. Object class toString method returns the hashcode of the object.
The output that you saw was the hashcode of the array object. So to print the values of the array object you need to iterate through it and print all the values. Or else other solution could be to use Collections like List or Set(i.e. dynamic array) which will print the values all the values within it when its toString() method is called.
Difference between collections like ArrayList and simple Array is that, List's can grow or shrink dynamically as needed(i.e. its size is variable). It also provides many in-build API methods to perform various operations on the List.