0

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

Jud
  • 1,324
  • 3
  • 24
  • 47

4 Answers4

2

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)

DangerDan
  • 519
  • 2
  • 13
0

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

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)

Community
  • 1
  • 1
LostBalloon
  • 1,608
  • 3
  • 15
  • 31
  • in short -> new StringBuilder(hi).reverse().toString() or for versions earlier than JDK 1.5, use java.util.StringBuffer – LostBalloon Mar 22 '14 at 05:22
0

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);

}   }
asmalindi
  • 49
  • 8