Two Laptop Bag
The moose likes Beginning Java and the fly likes Explain the output... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Explain the output..." Watch "Explain the output..." New topic

Explain the output...

Sadhu Yadav

Joined: Aug 22, 2005
Posts: 5
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) {

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

Joined: Aug 26, 2005
Posts: 824
For ur knowledge , c[0] is not a final variable........see the

it's a simple integer variable

Lack of will power has caused more failure than lack of intelligence or ability.
My Blog | Red5 Resources | Technology Update | Daily Technology Tips
Sravan Kumar
Ranch Hand

Joined: Sep 11, 2005
Posts: 121
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.

keep smilin :: sravan<br /><a href="" target="_blank" rel="nofollow">I scribble here</a>
Satish Chilukuri
Ranch Hand

Joined: Jun 23, 2005
Posts: 266
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

Joined: Aug 22, 2005
Posts: 5
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.
I agree. Here's the link:
subject: Explain the output...
It's not a secret anymore!