5.10 Parsing values

This lesson shows how to convert a string into another data type, typically an int. We declare String numberAsString = "2021"; and print it. The value displayed is 2021, but it is stored as text, not as a number, so we cannot do arithmetic with it directly.

Integer.parseInt

To convert it we call the helper method Integer.parseInt: int number = Integer.parseInt(numberAsString);. After this line, number contains the actual integer 2021. We can now apply arithmetic operators on it, while numberAsString is still the textual representation.

  • numberAsString + 1: Java converts the integer 1 to a string and concatenates it, producing "20211".
  • numberAsString += "1": explicit concatenation; the result is also a string.
  • number += 1: arithmetic addition; number becomes 2022.

Be careful: if the original string contains a letter like "A" or any special character, Integer.parseInt throws a NumberFormatException because the conversion is impossible. That is what makes parsing both useful and brittle, and it is why we will combine it with input validation in the following lessons.

Summary

This lesson teaches how to parse string values into integer types using Java's Integer.parseInt() method. The instructor demonstrates the crucial difference between string concatenation—where "2021" + 1 results in "20211"—and numeric addition—where 2021 + 1 results in 2022. The lesson also covers error handling, explaining that parsing non-numeric characters (letters or special symbols) will throw an exception since Integer.parseInt() cannot convert them.

Key points

  • Use Integer.parseInt() to convert string values to integers
  • String concatenation combines values as text ("2021" + 1 = "20211"), while numeric addition performs mathematical operations (2021 + 1 = 2022)
  • Java automatically converts number literals to strings in concatenation contexts
  • Parsing non-numeric characters (letters, special symbols) with Integer.parseInt() causes an exception
  • Understanding the distinction between string and numeric operations is critical for data type conversion

FAQ

What method converts a string to an integer in Java?

Use Integer.parseInt() which accepts a string as a parameter and returns the corresponding integer value.

Why does adding 1 to a string give a different result than adding 1 to an integer?

String concatenation combines values as text ("2021" + 1 = "20211"), while integer addition performs mathematical operations (2021 + 1 = 2022).

What happens if I try to parse a letter or special character with Integer.parseInt()?

An exception occurs because Integer.parseInt() cannot convert non-numeric characters to integers.