Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explain the output...

 
Sadhu Yadav
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which statement would cause a compilation error if inserted in the location indicated in the following program?

public class ParameterUse {
static void main(String[] args) {
int a = 0;
final int b = 1;
int[] c = { 2 };
final int[] d = { 3 };
useArgs(a, b, c, d);
}

static void useArgs(final int a, int b, final int[] c, int[] d) {
// INSERT STATEMENT HERE.
}
}


A) b++;

B) b = a;

C) c[0]++;

D) d[0]++;

E) c = d;

===========================================================

The correct answer is E. I would like to know why it is not C, as we are trying to change the value of a final variable.
 
Sunil Kumar Gupta
Ranch Hand
Posts: 824
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For ur knowledge , c[0] is not a final variable........see the
declaration...

it's a simple integer variable
 
Sravan Kumar
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a reference is declared final, it means you cannot change the value in the reference i.e. it cannot point to some other object. Whereas the value in that object can still be changed using this reference.

In the method, the local reference c is final. This means you cannot assign any other int[] reference, say d, to c. Option C changes the value in the array object (this object is not final, only its reference is). This is allowed.
 
Satish Chilukuri
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say c[0]++, you are not changing the value of the final refernce variable c, but changing the value of an int variable pointed to by c[0].

If you try to do something like this:

c = d;

then the compiler will complain because you trying to change the value of a final refernce variable.
 
Sadhu Yadav
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for ur responses.

I think Mr Sravan is very correct to point out that we cannot make a final reference variable to point to some other object but we can definetly change the value of the object pointed by it.

Thanks Sravan.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic