• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why local variables are prefered than instance Vraiables in this case

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Can anybody please let me know why is that we like to have Statements , Connections ---etc as local variables but not as instance Variables .

Thanks for reading , waiting for your replies .
 
Martin Vanyavchich
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because local variables have lesser scope and life span. As soon as the method finishes all objects that were declared in it and their reference wasn't passed on, are eligible for garbage collection. If those were instance variables, once initialized they will exist on heap until the instance of the class isn't eligible for gc. It's good practice to limit the scope and visibility of variables as much as we can.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Additionally, instance variables are shared by threads, so if you are instantiate the MyTableDAO as an instance variable in other class then, when more than one threads try to use the different methods[which are uses the same connection] from MyTableDAO , creates *problem*/race condition.

 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Martin and Seetha , It was a nice explanation .
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic