aspose file tools*
The moose likes Servlets and the fly likes Initialize int variable in servlets 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 » Servlets
Bookmark "Initialize int variable in servlets" Watch "Initialize int variable in servlets" New topic
Author

Initialize int variable in servlets

muntago Richard
Ranch Hand

Joined: Nov 13, 2010
Posts: 82
how do i set int variable in servlets request .

int id = Integer.getInteger(request.getParameter("id")).intValue();

i tried this but not working
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61430
    
  67

Define "not working".

And I'd use Integer.valueOf().


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
sadhu charan
Greenhorn

Joined: Nov 27, 2012
Posts: 18
Better you try

int id = Integer.ParseInt((request.getParameter("id"));
Sean Rowlandson
Greenhorn

Joined: Jan 05, 2013
Posts: 6
Not sure what you mean by not 'not working'.

However like what has already been posted the following should be fine:


int id = Integer.valueOf(request.getParameter("id")).intValue ();

William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12806
    
    5


The usual problem with this kind of shortcut appears when getParameter("id") returns null rather than the expected String and you get a null pointer exception.

Therefore, try to recover the parameter String first, test for null and then decide what to do.

Bill
Sean Rowlandson
Greenhorn

Joined: Jan 05, 2013
Posts: 6
Further to bills observation, any time you are dealing with objects such as requests it is good and advised practise to check for null first.

Including null checks is a good habit to get into in any code as it makes it more robust and also scales better... a few years down the line a joe bloggs decides to come along and use one of your methods then kindly passes a null value and.... POP.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Initialize int variable in servlets