Convert string to int

Hi

I'd like to convert string to int and make logical check like if(i < 0). Can you please help?

Thanks
hasozduruAsked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
int i = Integer.parseInt(s);
if (i<0){
   // less than 0
}


0
 
fargoCommented:
String test="23";

int tt =  Integer.valueOf(test).intValue();

if(tt>0){
// i m greater than 0
}
0
 
Siva Prasanna KumarConnect With a Mentor Principal Solutions ArchitectCommented:
try{
int i = Integer.parseInt(s);
}
catch(NumberFormatException e)
{
e.printStackTrace();
}

if(i<0)
{
//do something.
}

This is just an addon to Objects Comments as You need to handle Number Format Exception which may be casued if the String is not a valid integer. in the sense String num = "123a3" or so.

Thank You.
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
hiteshgupta1Commented:
Whats wrong with solution suggesed by Fargo??
0
 
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
Integer.valueOf(test).intValue();

nothing is wrong actually its a 2 steps first coverts String to Integer (wrapper Class ) and then to integer form Integer.

Its also good & effective.
0
 
fargoConnect With a Mentor Commented:
No. parseInt is more effective and better to use.

see here
http://www.javaworld.com/javaworld/javaqa/2000-11/03-qa-1117-integer.html
0
 
basicinstinctConnect With a Mentor Commented:
the try/catch block from shivaspk is essential - you should definitely incorporate that
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.