How to check if a given string is a valid integer in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s1 = "8762"; 
        String s2 = "340J"; 
          
        try 
        { 
            Integer.parseInt(s1); 
            System.out.println(s1 + " is a valid integer"); 
        }  
        catch (NumberFormatException e)  
        { 
            System.out.println(s1 + " is not a valid integer"); 
            System.out.println(e);
        } 
          
        try 
        { 
            Integer.parseInt(s2); 
            System.out.println(s2 + " is a valid integer"); 
        }  
        catch (NumberFormatException e) 
        { 
            System.out.println(s2 + " is not a valid integer");
            System.out.println(e);
        } 
    }
}



/*
run:

8762 is a valid integer
340J is not a valid integer
java.lang.NumberFormatException: For input string: "340J"

*/

 



answered Aug 20, 2019 by avibootz
edited Aug 20, 2019 by avibootz

Related questions

1 answer 201 views
1 answer 186 views
1 answer 164 views
4 answers 225 views
1 answer 158 views
2 answers 228 views
...