1

I am using the following:

int i = Integer.parseInt(args[2]);

Are there any other ways to get an integer from a string? If the number is really small as it is then doe the Byte and Char objects provide something similar?

4 Answers 4

2

Yes. There's:

Byte.parseByte(s); -- parses a Byte from a String
Short.parseShort(s); -- parses a Short from a String

And for larger numbers there's:

Long.parseLong(s);
-- Float is an imprecise representation of a floating point number using 32 bits
Float.parseFloat(s);
-- Double is an imprecise representation of a floating point number using 64 bits
Double.parseDouble(s);
-- BigIntegers is an integer of arbitrary size as is accurate
new BigInteger(s);
-- BigDecimal is a floating point number of arbitrary size as is accurate
new BigDecimal(s);
Sign up to request clarification or add additional context in comments.

2 Comments

I am getting the following error: int i4 = new BigInteger(args[3]); Type mismatch: cannot convert from BigInteger to int
To get an int from a BigInteger use .intValue(): ie i4 = new BigInteger(s).intValue();. The BigInteger class is for performing accurate integer arithmetic on arbitrarily large numbers. It has special methods for such arithmetic.
0

Yes, you can use the Short.parseShort(String) and Byte.parseByte(String) wrapper methods to parse smaller integer values.

Comments

0

Other ways to get an integer from a String:

    String value = "2";

    int i = Integer.valueOf(value);
    System.out.println("i = " + i);
    Scanner scanner = new Scanner(value);
    i = scanner.nextInt();
    System.out.println("i = " + i);

Comments

0

You also should wrap that in a try catch block so your code will not blow up if you try to pass it a non-integer value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.