• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

how does this piece of code work? forward referencing?

 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


[output : 0]

the question is... when exactly does j get the value of 10? the 'return j' statement returns a 'zero'. I expected it tobe a 10.

Please explain how the code works... i feel quite a lot is going on there which I don't understand. According to me, it should have ben a forward referencing error!

Thanks.
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you called giveJ() method, the variable was not intialized. So, JVM intialized it with a default value 0. That's why you're getting the result as 0 in the output.

A little modification in the code can sort this problem out. Here's your code with just a mere modification:

 
Pawan Arora
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
edit:nvm
 
author
Posts: 23958
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

the question is... when exactly does j get the value of 10? the 'return j' statement returns a 'zero'. I expected it tobe a 10.



Instance variables (that are not compile time constants) get initialized in the order that they appear in the source (from top to bottom, and left to right). And any forward reference to them, will have them at their default values.

Henry
 
Aakash Goel
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks. got it!
 
I like tacos! And this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic