Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variable initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable initialization" Watch "Variable initialization" New topic
Author

Variable initialization

Akhilesh Trivedi
Ranch Hand

Joined: Jun 22, 2005
Posts: 1526

This one show output as 0. why?
[ October 05, 2006: Message edited by: Akhilesh Trivedi ]

Keep Smiling Always — My life is smoother when running silent. -paul
[FAQs] [Certification Guides] [The Linux Documentation Project]
Sai Surya
Ranch Hand

Joined: Feb 08, 2006
Posts: 457

HI Trivedi,

This is because you are initializing j after calling the giveMeJ() method. So by the time you call this method j does not have any value except default value 0. If you change private int j = 10 before calling giveMeJ() it prints 10. Please do verify.

- Surya


Sai Surya, SCJP 5.0, SCWCD 5.0, IBM 833 834
http://sai-surya-talk.blogspot.com, I believe in Murphy's law.
Ali Gohar
Ranch Hand

Joined: Mar 18, 2004
Posts: 572
As you are accessing variable j before its initialization.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
This is a way to get around with the forward reference rule.
What are the forward reference rules?
ganeshraj selvaraj
Greenhorn

Joined: Oct 09, 2006
Posts: 3
Hi Trivedi,

When considering the variables
1- All INSTANCE VARIABLES will have the default value as the zero.

2- All LOCAL VARIABLES (i.e with in the method) should be initialised before use.No default value is allocated for those variables.

If you use the local variables without intialising then you will definitely get error.Similarly if you use the instance variables without intialising then you will not get the error because every instance variables will be having the default values.

Regards,
Ganeshraj S
Anvi Dixit
Ranch Hand

Joined: Aug 28, 2006
Posts: 45
Hello Trivedi,

If you wannt to have the value of the variable j as 10 instead of 0 , just add Private static int j = 10; instead of private int j = 10;

and then test . you will get the value as 10.

Thanks and Regards
Anvi
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Variable initialization
 
Similar Threads
another perplexing program
Variable initialization
forward refrerences
please explain why the compiler is not complaining and why the output is 0
one Construtor's problem?