How to check Type before casting in java

11,611

Solution 1

Try to parse the int and catch the exception if it fails:

String var1="5.5";

try {
 qt += Integer.parseInt( var1);
}    
catch (NumberFormatException nfe) {
// wasn't an int
}

Solution 2

First of all, your if condition will certainly fail, because the object reference actually points to a String object. So, they are not instances of any integer or double.

To check whether a string can be converted to integer or double, you can either follow the approach in @Bedwyr's answer, or if you don't want to use try-catch, as I assume from your comments there (Actually, I don't understand why you don't want to use them), you can use a little bit of pattern matching: -

String str = "6.6";
String str2 = "6";

// If only digits are there, then it is integer
if (str2.matches("[+-]?\\d+")) {  
    int val = Integer.parseInt(str2);
    qt += val;
}

// digits followed by a `.` followed by digits
if (str.matches("[+-]?\\d+\\.\\d+")) {  
    double val = Double.parseDouble(str);
    wt += val;
}

But, understand that, Integer.parseInt and Double.parseDouble is the right way to do this. This is just an alternate approach.

Solution 3

You can use patterns to detect if a string is an integer or not :

  Pattern pattern = Pattern.compile("^[-+]?\\d+(\\.\\d+)?$");
  Matcher matcher = pattern.matcher(var1);
  if (matcher.find()){
      // Your string is a number  
  } else {
      // Your string is not a number
  }

You will have to find the correct pattern (I haven't used them for awhile) or someone could edit my answer with the correct pattern.

*EDIT** : Found a pattern for you. edited the code. I did not test it but it is taken from java2s site which also offer an even more elgant approach (copied from the site) :

 public static boolean isNumeric(String string) {
      return string.matches("^[-+]?\\d+(\\.\\d+)?$");
  }

Solution 4

Maybe regexps could suit your needs:

public static boolean isInteger(String s) {
    return s.matches("[-+]?[0-9]+");
}

public static boolean isDouble(String s) {
    return s.matches("[-+]?([0-9]+\\.([0-9]+)?|\\.[0-9]+)");
}

public static void main(String[] args) throws Exception {
    String s1 = "5.5";
    String s2 = "6";
    System.out.println(isInteger(s1));
    System.out.println(isDouble(s1));
    System.out.println(isInteger(s2));
    System.out.println(isDouble(s2));
}

Prints:

false
true
true
false

Solution 5

Integer.parseInt and Double.parseDouble return the integer/double value of the String. If the String is not a valid number, the method will thrown a NumberFormatException.

String var1 = "5.5";

try {
    int number = Integer.parseInt(var1); // Will fail, var1 has wrong format
    qt += number;
} catch (NumberFormatException e) {
    // Do your thing if the check fails
}

try {
    double number = Double.parseDouble(var1); // Will succeed
    wt += number;
} catch (NumberFormatException e) {
    // Do your thing if the check fails
}
Share:
11,611

Related videos on Youtube

Syed Muhammad Mubashir
Author by

Syed Muhammad Mubashir

Syed Muhammad Mubashir Masters (CS) NUCES FAST Spring 2011. Graduation (CS) DCS KU Fall 2006 Working as Team Lead Backend/Database Development as Altpay. Worked as an Senior Software Engineer/Team Lead at Higher Visibility. Worked as an Team Lead at Higher Visibility. Worked as an Assistant IT Manager at Anila Gems Int. Worked as technical ERP consultant at VIBE TECHNOLOGIES. Jun 2008- Jun 2011 Worked as Lab Instructor at Fast-NU Fall 2010.

Updated on October 26, 2022

Comments

  • Syed Muhammad Mubashir
    Syed Muhammad Mubashir over 1 year

    I am casting my String variables to integer and double. I want to check whether the String variable contains valid Integer or Double value at runtime.

    I us following code but it not works for me.

    String var1="5.5";
    String var2="6";
    Object o1=var1;
    Object o2=var2;
    if (o1 instanceof Integer)
    {
        qt += Integer.parseInt( var1);// Qty
    }
    if (o2 instanceof Double)
    {
        wt += Double.parseDouble(var2);// Wt
    }
    
    • giorashc
      giorashc over 11 years
      o1 and o2 are definitely not instance of Integer as they both reference a String object
  • Syed Muhammad Mubashir
    Syed Muhammad Mubashir over 11 years
    I know this technique but i want to avoid excpetion to occur
  • Rohit Jain
    Rohit Jain over 11 years
    @SyedMuhammadMubashir.. This is what we call avoiding Exception to occur. We should handle them. And whether exception is raised or not, completely depends upon what string you are trying to convert. Of course you cannot convert "".
  • TheBlastOne
    TheBlastOne over 11 years
    You might want to look at stackoverflow.com/questions/9619603/no-tryparsedouble-in-jav‌​a, or the question that one is a duplicate of.
  • sp00m
    sp00m over 11 years
    @SyedMuhammadMubashir Are you dealing reputation?! I won't upvote your question, but you're free not to upvote mine ;)
  • Rohit Jain
    Rohit Jain over 11 years
    @SyedMuhammadMubashir.. I assume that you are asking questions on SO, to learn something, and not to buy Reputation. If you are doing so for the later, then rather answer the questions here. And give very good answers, if you know them. Don't urge people here to upvote your posts.