Devpiaa
Devpiaa

Reputation: 1

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

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

Upvotes: 0

Views: 33

Answers (1)

RadekJ
RadekJ

Reputation: 3043

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.

Upvotes: 1

Related Questions