Two Laptop Bag*
The moose likes Java in General and the fly likes Why local variables are prefered than instance Vraiables in this case Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why local variables are prefered than instance Vraiables in this case " Watch "Why local variables are prefered than instance Vraiables in this case " New topic
Author

Why local variables are prefered than instance Vraiables in this case

Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

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 .

Save India From Corruption - Anna Hazare.
Martin Vanyavchich
Ranch Hand

Joined: Sep 16, 2008
Posts: 241
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.


SCJP 6, OCMJD 6, OCPJWSD 6
I no good English.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

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

Joined: Apr 18, 2009
Posts: 2234

Thanks Martin and Seetha , It was a nice explanation .
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

you are welcome
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why local variables are prefered than instance Vraiables in this case
 
Similar Threads
jdbc connection suddenly closed
Simple JDBC problem - Connection throws Nullpointerexception
java.sql.SQLException: Closed Connection
When to use Instance vs Local variables
diff between con=null and con.close()