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 char
acters, @
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
How to Compare Objects by Multiple Fields
Random Errors When Changing Series Using Jfreechart
Java Arrays Printing Out Weird Numbers and Text
Json Parsing Using Gson For Java
How to Convert Milliseconds to "X Mins, X Seconds" in Java
Are Fields Initialized Before Constructor Code Is Run in Java
How to Set the Java.Library.Path from Eclipse
Why Aren't Java Collections Remove Methods Generic
Getting a File'S Md5 Checksum in Java
Jtextfields on Top of Active Drawing on Jpanel, Threading Problems
Why Is the Java Main Method Static
How to Get the Separate Digits of an Int Number
Check Whether a String Is Not Null and Not Empty
How to Read from a Inputstream With a Timeout
Why Is There No Sortedlist in Java
In Java, Is the Result of the Addition of Two Chars an Int or a Char