File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Object creation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object creation " Watch "Object creation " New topic
Author

Object creation

kannan vinayagam Duraiswamy
Ranch Hand

Joined: Jan 12, 2009
Posts: 52

code 1


code 2



what is the difference between these two codes
in code 2 : is the new arraylist object is created very time the loops run?.
in code 1 : only one arrauylist is created?.


Kannan.DV
Balu Sadhasivam
Ranch Hand

Joined: Jan 01, 2009
Posts: 874




Is the new arraylist object is created very time the loops run?.


Yes for both code 1 and 2
Kumari Priyanka
Greenhorn

Joined: Dec 29, 2008
Posts: 7
In first case only one ArrayList object will be created in the heap.... while in second case 10 new ArrayList object will get created.....
Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
In first case only one ArrayList object will be created in the heap.... while in second case 10 new ArrayList object will get created.....



Do you mean reference handlers? Anyways, both coding styles shouldnt matter as the gc will take care of the short-lived references.
Kumari Priyanka
Greenhorn

Joined: Dec 29, 2008
Posts: 7
yes.....gc will take care of the short lived references.....but the first is the best practice that you should follow......
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

Kumari Priyanka wrote:yes.....gc will take care of the short lived references.....but the first is the best practice that you should follow......


I disagree. If a variable is meant to be limited to a certain scope it shouldn't be declared outside of that scope, because it may then inadvertently escape its inteded scope.
If you minimize the scope of the variable this cannot happen and the variable will be more readily recognizable as a local variable to programmers that will have to maintain the code.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
 
GeeCON Prague 2014
 
subject: Object creation