Search code examples
javavariablesfinal

Java final variable in a function


I always thought that final variables are only assigned once. Can someone please enlighten me on what the final keyword does in this case? Does it mean that it is only "final" until the function returns?

public void onClick(View view) {
    final int x = new Random().nextInt();
    System.out.println(x);
}

Output:

03-01 14:18:25.022: I/System.out(26253): 416604980
03-01 14:18:25.332: I/System.out(26253): -1080822415
03-01 14:18:25.522: I/System.out(26253): -170506517
03-01 14:18:26.982: I/System.out(26253): 1438898132
03-01 14:18:27.112: I/System.out(26253): 401245673

Solution

  • x, as a final local variable, can be assigned only once within the scope of its existence, which is the body of the onClick method.

    Each call to that method creates a new x variable that can only be assigned once.