Programmers are often faced with tasks whose solutions are not always obvious. One such task is string parsing. It is used when reading data from the console, file and other sources. Most data transmitted over the Internet is also in row form. Unfortunately, it is impossible to perform mathematical operations with strings. Therefore, every programmer needs to know exactly how to convert a string to a number in Java. Strings can contain different numeric types:
- byte;
- short;
- int;
- long;
- float;
- double.
byte a = Byte.parseByte("42");
short b = Short.parseShort("42");
int c = Integer.parseInt("42");
long d = Long.parseLong("42");
float e = Float.parseFloat("42.0");
double f = Double.parseDouble("42.0");
It is no secret that the most popular data type is int
, therefore, in terms of the frequency of its use, the method parseInt
in Java breathes in the back of the method for outputting information to the console System.out.println()
. But when using the method, Integer.parseInt()
you need to remember some nuances:
-
If you pass a string that is not an integer value to a method, you will receive an error
java.lang.NumberFormatException
indicating that the resulting string is not an integer value. -
NumberFormatException
will also happen if the passed string contains a space. -
parseInt()
- can work with negative numbers. To do this, the line must begin with the “-” character. -
parseInt()
— cannot parse a string if the numeric value is outside the type limitsint
(-2147483648 .. 2147483647).
GO TO FULL VERSION