Parse String to Int with default value - Java java.lang

Java examples for java.lang:int Parse

Description

Parse String to Int with default value

Demo Code

public class Main {
  public static void main(String[] argv) {
    String b = "java2s.com";
    System.out.println(toInt(b));

    b = "false";//from   ww w.  j  a v  a  2s  . co m
    System.out.println(toInt(b));

    b = "1";
    System.out.println(toInt(b));

    b = "yes";
    System.out.println(toInt(b, 2));
  }
  public static int toInt(String str, int defValue) {
    try {
      return Integer.parseInt(str);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return defValue;
  }

  public static int toInt(Object obj) {
    if (obj == null) {
      return 0;
    }
    return toInt(obj.toString(), 0);
  }

}

Related Tutorials