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 a char[]
back to a String
. You could also use Arrays.toString(arr)
Related trivia
The reason that your arr.toString()
method returns something like [Cf4e6d
is that Object.toString
returns
getClass().getName() + '@' + Integer.toHexString(hashCode())
For a char
array, getName()
returns the string [C
. For your program you can see this with the code:
System.out.println(arr.getClass().getName());
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 different arr.toString()
values for two arrays based on the same string:
String s = "fdsa";
char[] arr = s.toCharArray();
char[] arr2 = s.toCharArray();
System.out.println(arr.toString());
System.out.println(arr2.toString());
gives:
[C@4b7c8f7f
[C@5eb10190
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 use string1.equals(string2)
to test for string equality, and not ==
as the ==
method will still test for memory location.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With