2
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?

Matt
  • 14,906
  • 27
  • 99
  • 149
gursahib.singh.sahni
  • 1,559
  • 3
  • 26
  • 51

2 Answers2

6

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].

Thihara
  • 7,031
  • 2
  • 29
  • 56
  • Note that arrays (even arrays of primitives) are objects in Java. Objects are handled via a reference, and if the 'final' keyword is applied only the reference to the object is final, not the object's members. – Adriaan Koster Mar 10 '13 at 09:01
3

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
giorashc
  • 13,691
  • 3
  • 35
  • 71