I want to convert a character array to a string object using the toString() method in java. Here is a snippet of the test code I used:
import java.util.Array
char[] Array = { 'a', 'b', 'c', 'd', 'e', 'f' };
System.out.println(Array);
It should print abcdef
.
The default implementation of the toString method of the char [] class returns a String representation of the base address of the array, which is what is being printed here. We cannot change it, since the class of char [] is not extendable.
Arrays don't override toString
. There's a static method: java.util.Arrays.toString
that should solve your problem.
import java.util.Arrays;
class toString {
public static void main(String[] args){
char[] Array = {'a', 'b', 'c', 'd', 'e', 'f'};
System.out.println(Arrays.toString(Array));
}
}
There is a spelling mistake of "Array.toString()" to "Arrays.toString(Array)" I guess so, and instead of writing name.toString(), pass the name as an argument and Write as above.
Just use the following commands to get your abcdef array printed
String a= new String(Array);
System.out.println(a);
there you have it problem solved !! now regarding why is printing the other stuff i think those guys above put some useful links for that. Ok gotta go !!
Because a char array is an array of primitives and toString() will give you it's default (which is a hash of the object). Some classes will implement toString() to do cooler things, but primitaves will not.