1

In my java program i have a local stringbuffer variable and i am passing that variable to another function.Now any changes in the other function is modifying the orignal variable also.How do i avoid this?please help.

the code:

main()
{
    ...
    StringBuffer in=....
    //n is the length of in
    for(int j=1;j<=n/2;j++)
        if(flipandcheck(in,j))
        {
            output=j+1;
            break;
        }
    ...
}
public static boolean flipandcheck(StringBuffer str,int index)
{
    int l=1;
    if(str.charAt(index)=='(')
        str.setCharAt(index,')');
    else 
        str.setCharAt(index,'(');
    for(int i=1;i<str.length();i++)
    {
        if(str.charAt(i)=='(')l++;
        else --l;
        if(l<0)return false;
    }
    if(l==0)return true;
    else return false;
}
duncan
  • 1,161
  • 8
  • 14
Harsh Rewari
  • 15
  • 1
  • 4

2 Answers2

1

You have to create a copy of the original StringBuffer and pass it to the function. Otherwise, you are passing a reference to the same StringBuffer object, so that the changes made inside the function are made against the local StringBuffer object.

Vicente Freire
  • 258
  • 1
  • 6
0

Create a copy of the buffer and pass it.

for(int j=1;j<=n/2;j++) {
    if(flipandcheck(new StringBuffer(in),j)) {
            output=j+1;
            break;
    }
}

Then, you might want to review this question.

Community
  • 1
  • 1
bradimus
  • 2,472
  • 1
  • 16
  • 23