Java Program to check if a string is a valid number

Java 8Object Oriented ProgrammingProgramming

To check if a string is a valid Integer, use the Integer.parseInt() method, with the string to be checked passed as a parameter.

To check if a string is a valid Float, use the Float.parseFloat() method, with the string to be checked passed as a parameter.

The following is an example that checks for valid integer.

Example

 Live Demo

public class Demo {
   public static void main(String args[]) throws Exception {
      String id = "100";
      int val = Integer.parseInt(id);
      System.out.println(val);
   }
}

Output

100

The following is an example that checks for valid float.

Example

 Live Demo

public class Demo {
   public static void main(String args[]) throws Exception {
      String id = "100.5";
      float val = Float.parseFloat(id);
      System.out.println(val);
   }
}

Output

100.5
raja
Published on 10-Dec-2018 13:09:00
Advertisements