wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt regarding final static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt regarding final static" Watch "Doubt regarding final static" New topic
Author

Doubt regarding final static

Amitkumar Dhama
Ranch Hand

Joined: Feb 14, 2005
Posts: 56
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.......


SCJP 1.4, SCWCD 1.4, M.Tech(CSE)
M Rama
Ranch Hand

Joined: Mar 04, 2005
Posts: 91
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

Joined: Feb 14, 2005
Posts: 56
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt regarding final static
 
Similar Threads
forward referencing for static variable??
Static Initialization Sequence
Ques on operator
Static Int and Methods
StringBuffer