I was trying to implement a string reversal algorithm by using two pointer variables at each end of the string where i points to the beginning and j points to the end. The elements at these places are swapped and then i and j are incremented and decremented respectively until i is less than j and i not equal to j. I am storing the string in a character array while doing this since string is immutable in java. However, when I am trying to convert this character array back to a string using the toString() method it is displaying random values. I know the code is correct since if I output the character array it displays the right values.
public class switcher {
int i=0,j;
char temp;
public void reverse(String s){
char [] ar = s.toCharArray();
j=ar.length-1;
while(i!=j&&i<j){
temp = ar[i];
ar[i]=ar[j];
ar[j]=temp;
i++;
j--;
}
String b=ar.toString();
System.out.println(b);
System.out.println(ar);
}
The output is as follows for the two print statements:
amistad [C@22a79c31 datsima
As you can see the string output is not correct. However, the array output is perfect. Please tell me what I am doing wrong.