File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable initialization" Watch "Variable initialization" New topic

Variable initialization

Akhilesh Trivedi
Ranch Hand

Joined: Jun 22, 2005
Posts: 1599

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: 463

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, 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

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.

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
I agree. Here's the link:
subject: Variable initialization
It's not a secret anymore!