This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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 Java 8 in Action this week in the Java 8 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: 60077
    
  65

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: 15
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: 12682
    
    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

Java Resources at www.wbrogden.com
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Initialize int variable in servlets
 
Similar Threads
Array
Weird update vs insert vs select from DB
Understanding Inner Class Output
a question about static clause
Understanding Objects and Reference Variables