I have this code where I am printing a string variable. The first output is showing what is expected but the second time it prints some unreadable output(I think its reference id). Please explain: Why does this happen?
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return c.toString();
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
}
}
Output:
boy
[C@60aeb0
the frontToBack() method is calling toString()
on a character array object char[]
which is why you see the [C@60aebo
. Instead of calling toString()
return with new String(c);
or String.valueOf(c)
Array types in Java do not override Object#toString()
. In other words, array types inherit Object
's implementation of toString()
which is just
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
which is the output you see
[C@60aeb0
If you want to see a representation of the contents of an array, use Arrays.toString(..)
.
In your case, you seem to want to switch the first and last characters and return the corresponding string. In that case, just create a new String
instance by passing the char[]
to the constructor.
You don't need to implement a custom class to do this. The functionality is already in java. This question has already been answered @ Reverse a string in Java (duplicate thread)
use new String(c) to c.toString();
c.toString() c mean array of chars toString() print hash method
public class Str3 {
public String frontBack(String str) {
char c[] = str.toCharArray();
char temp = c[0];
c[0] = c[c.length - 1];
c[c.length - 1] = temp;
return new String(c);
}
public static void main(String args[]) {
Str3 s = new Str3();
String s1 = new String("boy");
System.out.println(s1);
String s2 = s.frontBack("boy");
System.out.println(s2);
} }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.