Search code examples
javastringbuffer

why the StringBuffer does not change?


public class Test1{
public static void main(String[] args){
    StringBuffer s=new StringBuffer("abcde");
    reverseString(s);
    System.out.println(s);
}
public static int reverseString(StringBuffer s){
    StringBuffer s1=new StringBuffer("");
    int length=s.length();
    for(int i=length-1;i>=0;i--){
        s1.append(s.charAt(i));

    }
    s=s1;
    return 1;
}

}

I want change the StringBuffer.In the method,s="edcba",but i run the class,the result is ”abcde".Why?


Solution

  • In JAVA, variables are always passed by val and what you're attempting to do, the variable needs to be passed by ref. In order to do what you want to do, the reference can't change, but the properties of the object CAN.

    public static int reverseString(StringBuffer s){ 
        StringBuffer s1=new StringBuffer(""); 
        int length=s.length(); 
        for(int i=length-1;i>=0;i--){ 
            s1.append(s.charAt(i)); 
    
        } 
        s.replace(0, length, s1.toString()); 
        return 1; 
    }