Java Arrays Printing Out Weird Numbers and Text

tostring() method in java displaying odd values

If you want to print String which should be based on array of character then you should wrap this array with new String object. So instead of

String b = ar.toString();

use

String b = new String(ar);

You need to know that arrays inherit toString() method from Object so its code returns

getClass().getName() + "@" + Integer.toHexString(hashCode());

which means you will see [C as result of getClass().getName() which represents one dimensional array of characters, @ token and hexadecimal form of arrays hexcode 22a79c31.


In case you would want to print content of array with different type of data than char you wouldn't be able to wrap it in String. Instead you will have to iterate over each elements and print them. To avoid writing your own method for this Java gives you java.util.Arrays class with toString(yourArray) method which will iterate over each elements of array and generate String in form

[element0, element1, element2, ... , elementN-1]

I get these weird characters when I try to print out a vector element!

Integer[] a = new Integer[1];
a[0] = new Integer(5);
List list = Arrays.asList(a);
System.out.println(list.get(0));

The above works as you would expect.

So it looks like the "int" array is treated like an Object and not an array of Integers. In other words auto boxing doesn't seem to be applied to it?

Array is initializing more elements than told too

[l@1f96302 is the default way an Object is printed (that's what Object's toString() method returns for arrays). Try System.out.print(Arrays.toString(list)) instead, which will display the elements of the array.

Java outputs garbage?

x1.toString() calls the toString() method on the x1 array.

Which returns something like [C@33909752. Which is the value returned by the Object.toString() method.

[ - it's an array
C - of type `char`
33909752 - on memory address `33909752`

If you want to build a String based on the characters in array x1 you must use new String(x1).



Related Topics



Leave a reply



Submit