Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding final static

 
Amitkumar Dhama
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the following lines inside class and outside of main method...
-----------------------------------
final static int p = abc();
final static int abc()
{
int i = 123;
System.out.println(p);
return i;
}
----------------------------------
if with the above code i am writing empty main method i am getting output
"0" after compiling and running
---------------------------------
And if i am printing the value of "p" inside main method then i am getting output "0" and "123"
As p is final, once it is initialized it can't be
assigned the value again....
And as far as i know final are not given any default valuethey must be assigned the value explicitly before the constructor completes.....
Thanking in adevance.......
 
M Rama
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amit,
If you don't mind, can you tell, where you are getting these questions from?

To answer your question:

final variables are not initialized until the constructor is run. however, this is a final static, which to my mind, means, this in not related with a constructor 'cos its static.

it will try to run the method and assign itself . if the same variable is reference from inside, its surely not going to have a value.

i don't see any purpose in this code and hence i was wondering if such questions will come up in the exam. surely no one will need to use such circular reference in the real world.

anyway, to give a little more idea for you to see the answer:

look at the following program:



will print:
x=null
x=null

ofcourse return x; could be changed to return "abc"; or an other string, which will get assigned to x.
 
Amitkumar Dhama
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rama,
thax 4 ur rep.I found it one of the mock exam on the net i am nt able to remember frm where..
in ur code if String var. is being initialized to say, "Rama" and then if we will return the var, we will get two values for a final variable....

X = null
X = Rama
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic