Use static method Integer.parseInt() and catch the exception that is thrown when the number cannot be parsed.
String s = "123";
boolean isValidInteger = false;
try
{
int i = Integer.parseInt(s);
// s is a valid integer
isValidInteger = true;
}
catch (NumberFormatException ex)
{
// s is not an integer
}
written by objects
\\ tags: int, string, validation
String s = "321";
boolean isNumber = s.matches("-?\\d+");
written by objects
\\ tags: int, regexp, string
You can either use the static toString() method in the Integer class, or string concatenation can also be used. We’d recommend using the toString() method.
int i = 123;
String s = Integer.toString(i);
// An alternative would be to use
// the following string concatenation
String s2 = "" + i;
written by objects
\\ tags: conversion, int, string
Recent Comments