The output for following two code blocks in Java is different. I am trying to understand why.
private String sortChars(String s){
char[] arr = s.toCharArray(); //creating new char[]
Arrays.sort(arr); //sorting that array
return new String(arr);
}
This one returns a string with sorted characters as expected.
private String sortChars(String s){
char[] arr = s.toCharArray(); //creating new char[]
Arrays.sort(arr); //sorting that array
return arr.toString();
}
Sorry. My bad! Using to compare two strings. The output to second string looks like this as suggested by many - [C@2e0ece65
Thanks!
In Java,
toString
on an array prints[
, then a character representing the array element type (C
in this case) and then the identity hash code. So in your case, are you sure it is returning the original string and not something like[C@f4e6d
?Either way, you should use
new String(arr)
. This is the shortest, neatest, way of converting achar[]
back to aString
. You could also useArrays.toString(arr)
Related trivia
The reason that your
arr.toString()
method returns something like[Cf4e6d
is thatObject.toString
returnsFor a
char
array,getName()
returns the string[C
. For your program you can see this with the code:The second part of the result,
Object.hashCode()
, returns a number based on the object's memory address, not the array contents. This is because by default the definition of "equals" for an object is reference equality, i.e. two objects are the same only if they are the same referenced object in memory. You will therefore get differentarr.toString()
values for two arrays based on the same string:gives:
Note that this is different for the
String
class where the equality rules are overridden to make it have value equality. However, you should always usestring1.equals(string2)
to test for string equality, and not==
as the==
method will still test for memory location.