Europa
Europa

Reputation: 147

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?

Upvotes: 1

Views: 175

Answers (2)

Chris Gessler
Chris Gessler

Reputation: 23113

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

Upvotes: 2

Marcus Johansson
Marcus Johansson

Reputation: 2667

You only change the StringBuilder s1 in the reverseString function. So the s StringBuilder in the main will be the same. Instead you should return s1 when you are done.

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

Upvotes: 1

Related Questions