What does "final" do if you place it before a variable?

Viewed 32686

Very basic question, but, what does "final" do if you place it before a variable such as below...

final EditText myTextField = (EditText) findViewById(R.id.myTextField);

What does final do?

8 Answers

Trying to explain use of final modifier with flow of code:

public static void main(String[] args) {

    class Person {
        String name;
    }

    Person peep1 = new Person(); // points to obj at address HEX001
    peep1.name = "Mike"; 
    System.out.println(peep1.name);

    Person peep2 = new Person(); // points to obj at address HEX002
    peep2.name = "Jenna";
    System.out.println(peep2.name);

    final Person peep3 = peep1; // also points to obj at address HEX001
    System.out.println(peep3.name);

    peep1.name = "pwnd"; // modifies obj at address HEX001
    System.out.println(peep1.name);
    System.out.println(peep3.name);

    peep1 = peep2; // now it points to obj at address HEX002
    System.out.println(peep1.name);

    System.out.println(peep3.name); // still points to obj at address HEX001

    peep2.name = "Henna"; // modifies obj at address HEX002
    System.out.println(peep2.name);

    peep3 = peep2; // compiler error "The final local variable peep3 cannot be assigned. It must be
                    // blank and not using a compound assignment"

    System.out.println(peep3.name); // assuming it now points to obj at address HEX002

}

Output:

Mike
Jenna
Mike
pwnd
pwnd
Jenna
pwnd
Henna
Related