How to determine whether char or int

Discussion in 'Java' started by Guest, Mar 20, 2005.

  1. Guest

    Guest Guest

    Hi,
    Given a string, how do you determine whether its of primitive type int or
    primitive type char?

    Thanks
     
    Guest, Mar 20, 2005
    #1
    1. Advertisements

  2. Guest

    Wiseguy Guest

    It's niether...it is a string until you do some tests on it to determine
    whether is can be represented in some other format.
     
    Wiseguy, Mar 20, 2005
    #2
    1. Advertisements

  3. Guest

    Edwin Martin Guest

    Java is not C!

    In OOP you don't have to know the inside of an object. Maybe the String
    is stored as gzipped EBCDIC. You don't care. As long as the API is
    correctly implemented. The fact that Java supports Unicode gives a clue,
    though.

    Edwin Martin
     
    Edwin Martin, Mar 20, 2005
    #3
  4. Guest

    Tom Dyess Guest

    I prefer this method. If it doesn't cast properly using the Integer object,
    it will throw an exception.

    public static boolean isNumeric(String s) {
    try {
    Integer i = new Integer(s);
    return true;
    } catch (Exception e) {
    return false;
    }
    }
     
    Tom Dyess, Mar 20, 2005
    #4
  5. Guest

    R.F. Pels Guest

    Can you explain a bit further, for example with a code snippet?
     
    R.F. Pels, Mar 20, 2005
    #5
  6. Why not just use Integer.parseInt(s)? No need to create a throwaway Integer object. In
    either case, don't bother assigning it to anything.

    Lastly, use the specific exception, NumberFormatException. It's clearer.

    public static boolean isNumeric(String s) {
    try {
    Integer.parseInt(s);
    return true;
    } catch (NumberFormatException e) {
    return false;
    }
    }

    .... much nicer ;^)
     
    Lee Fesperman, Mar 20, 2005
    #6
  7. Guest

    Tom Dyess Guest

    Kewl, didn't even know that existed.
     
    Tom Dyess, Mar 21, 2005
    #7
  8. It's perfect when you need the value but only as a primitive.

    BTW, using java.lang.Exception instead of NumberFormatException would be proper if you
    also wanted to cover a null reference.
     
    Lee Fesperman, Mar 21, 2005
    #8
  9. Guest

    Ryan Stewart Guest

    [...]
    Not really. Then you'd add a catch block for a NullPointerException or mention
    in the documentation that if you pass a null reference, the method will throw a
    NullPointerException, which should pretty well be common sense anyhow.
     
    Ryan Stewart, Mar 21, 2005
    #9
  10. Yep, I'll go along with that.
     
    Lee Fesperman, Mar 21, 2005
    #10
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.