Home > front end >  In android, why does Local variable which is not declared by final work at ClickListener?
In android, why does Local variable which is not declared by final work at ClickListener?

Time:12-09

In following code, why does local variable which is not declared final work in the ClickListener?? Local variables without final are destroyed at the end of the onCreate method, so it shouldn't be accessible in the OnClickListener, right? But, in the following code the value of a is shown in the Toast. I don't understand why...

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String a = "a";

        Button btnMinus = findViewById(R.id.btnMinus);

        btnMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, a, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

CodePudding user response:

Because it is effectively final.

But if you add

String a = "";
a = "a";

and leave the rest of your code unchanged, then it will fail to compile as it wont be effectively final anymore.

CodePudding user response:

you're saying 'value of "result"', but there is no any variable named result and local variables do not get destroyed at end of function they still exist but they are not accessible outside body of the function.

  • Related