Academic Java    Java Tutorial  >  Strings  >  convert string to numbers

convert string to numbers Example

Java convert string to numbers EXAMPLE output Any string representing a primitive type i.e. char boolean short byte int long float double can be converted to its primitive value using a parse method of the primitive's wrapper class.

For example, the method Integer.parseInt() takes a string as parameter and converts it to its primitive int value. If the string could not be converted to an int, for example if it contained a decimal point, then an exception would be thrown.
// Convert string to numbers (ints, doubles) and booleans
class ConvertStringToNumberExample {

   public static void main(String[] args) {

      String s = "2345";
      int i = Integer.parseInt(s);
      System.out.println("i="+i);

      s = "0.00173";
      double d = Double.parseDouble(s);
      System.out.println("d="+d);

      s = "true";
      boolean b = Boolean.parseBoolean(s);
      System.out.println("b="+b);

   }
}