File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable initialization

 
Akhilesh Trivedi
Ranch Hand
Posts: 1599
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This one show output as 0. why?
[ October 05, 2006: Message edited by: Akhilesh Trivedi ]
 
Sai Surya
Ranch Hand
Posts: 463
Eclipse IDE Java Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ali Gohar
Ranch Hand
Posts: 572
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you are accessing variable j before its initialization.
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a way to get around with the forward reference rule.
What are the forward reference rules?
 
ganeshraj selvaraj
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic