Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final keyword preceding the parameter declaration in method declaration

class hello {
    public static void main(String arg[]){

    int[] c = { 2 };
    final int[] d = { 3 };

    }

static void useArgs(final int a, int b, final int[] c, int[] d) {

    c[0]=d[0]; // no error 
    c = d; //error 
    }
 }

guys can anybody can explain this behavior?

like image 290
gursahib.singh.sahni Avatar asked Jul 24 '26 21:07

gursahib.singh.sahni


2 Answers

Variable c is final. Which means that you cannot assign another value to that variable.

But the elements in the array itself are not final, which is why you are able to change the assignment on the elements like c[0]=d[0].

like image 89
Thihara Avatar answered Jul 26 '26 11:07

Thihara


c is a final (const) reference to an array of ints. and since c is final you cannot change its value (i.e change the address it refers to). And this goes for any variable declared as final (not just arrays).

This also won't work :

final int c = 1;
int d = 2;
c = 2; // Error
c = d; // Error
like image 20
giorashc Avatar answered Jul 26 '26 10:07

giorashc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!