JavaRush /Java Blog /Random EN /Parsing Strings in Java

Parsing Strings in Java

Published in the Random EN group
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. Parsing strings in Java - 1Strings can contain different numeric types:
  • byte;
  • short;
  • int;
  • long;
  • float;
  • double.
To extract a numeric value of the required type from a string, you need to use its wrapper class:

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 parseIntin 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:
  1. If you pass a string that is not an integer value to a method, you will receive an error java.lang.NumberFormatExceptionindicating that the resulting string is not an integer value.

  2. NumberFormatExceptionwill also happen if the passed string contains a space.

  3. parseInt()- can work with negative numbers. To do this, the line must begin with the “-” character.

  4. parseInt()— cannot parse a string if the numeric value is outside the type limits int(-2147483648 .. 2147483647).

Considering these four simple nuances, you can avoid complex mistakes in the future, because programmers have to parse strings very often. And this awaits each of us!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION