Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instance variables and local variables

 
Vinayak patil
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does Java provide a default value to instance variables and does not do so to local variables (variables declared in a method) ? Is there a difference in the way they are handled?
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance variables represent the object on the heap while local variables are on the stack. To initialize local variables java would have to insert code at the top of every method to update those stack-resident variables, which means a memory write for every local variable. The cummulative effect would be very signficant and it's usually redundant: locals are always set before they are used.
 
Vinayak patil
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot! for the response
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic