aspose file tools*
The moose likes Java in General and the fly likes When to use Integer or new Integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When to use Integer or new Integer" Watch "When to use Integer or new Integer" New topic
Author

When to use Integer or new Integer

Steve Dyke
Ranch Hand

Joined: Nov 16, 2004
Posts: 1466
    
    1
Can someone tell me which I should use and explain?




Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4421
    
    8

It depends on what the attribute stored in the session actually is.

If it's an Integer object, there's absolutely no point converting it to a String and then back to an Integer. Just cast it straight to an Integer, as in the first approach.

If it's really a String, I'd cast it to a String and then use Integer.parseInt to convert it:
int edindex = Integer.parseInt((String)request.getSession().getAttribute("e8DIndexNumber"));

I don't think I'd ever use your second form exactly like that.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Matthew Brown wrote:I don't think I'd ever use your second form exactly like that.

Agreed. One should never use the new keyword to convert to an Integer unless a new instance is required.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

Which is just about never. All of the primitive-wrapper classes have static valueOf methods which may use cached objects, reducing the memory footprint of your application. You should use those as much as possible. I never use new in combination with the primitive-wrapper classes anymore.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use Integer or new Integer