Can We change the final StringBuffer Reference?.... Please Explain

Hi,
I expected Error in the following code, but it is running well and giving output as below:
FirstTime Added
SecondTime
FirstTime Added
The code is as follows...
public class Test1 {
     static final StringBuffer sb= new StringBuffer("FirstTime");
     public static void method(StringBuffer sb){
          sb.append(" Added");
     System.out.println(sb);
     sb = new StringBuffer("SecondTime");
     System.out.println(sb);
     public static void main(String a[]){
     method(sb);
     System.out.println(sb);
     }

I expected Error in the following code, but it is running well and giving output as below:
What error were you hoping for??
I think the answer to the question you haven't actually asked but wanted to, is that within method(), "sb" is a local (method-scope) reference, and is not the same reference as the field "sb" - whereas there is no method-scope "sb" variable in the main() method and so it uses the static field with that name.
For clarity, I always prefix field references with their scope modifiers, ie "Test1.sb" to refer to your static field, or "this.sb" if it were an instance field - compared to simply "sb" for a method-scope variable. Makes it easier to read - though naturally, not reusing the same variable name has a rather larger bearing on that :o)

Similar Messages

Maybe you are looking for