Java - final variable requirement in OnClickListener
<p>I have a program which has a text box that the user can edit. When the user presses a button a Dialog box is created, displaying the user's text and a confirm 'yes/no' option.</p>

<pre><code>public void setIP(View v){
    //get the text inside the editor
    EditText et = (EditText) findViewById(R.id.editTextIP);
    final String IP = et.getText().toString();

    //create dialog 
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Set I.P. to : " + IP + " ?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    host = IP;
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}
</code></pre>

<p>This code works fine, but my first version would not compile. My IDE complained that I should make the string <code>IP</code> <code>final</code>, when It was not.</p>

<p>This got me thinking. What does <code>final</code> add in this case? What if, for example, I chose to keep a reference to the Dialog, and show it from another method. This means the method above will have returned. So how can the variable <code>IP</code> linger on? </p>

<p>Does the final keyword just ensure the value isn't changed elsewhere, allowing the onClickListener to store the value of <code>IP</code>, knowing it will still be true? is the scope of <code>IP</code> increased?</p>
