How to Convert a String to an Int in Java

Java is a strongly typed language, which means it enforces strict rules about data types. A value stored as a String — even if it looks like a number — cannot be used in arithmetic, comparisons, or numeric logic until it's explicitly converted to an integer type. Knowing how and when to do that conversion is a fundamental skill in Java development.

Why Strings and Ints Are Not Interchangeable

In Java, a String is an object that holds a sequence of characters. An int is a primitive data type that holds a 32-bit signed integer. Even if a String contains "42", Java treats it as text, not a number. Trying to add "42" + 8 doesn't give you 50 — it gives you "428" through string concatenation.

This distinction matters whenever your program reads input from a user, pulls data from a file, parses a URL parameter, or processes an API response. Data arriving from outside your program almost always comes in as a String, and converting it correctly is a necessary step before doing anything numeric with it.

The Primary Method: Integer.parseInt()

The most common and direct way to convert a String to a primitive int in Java is with Integer.parseInt().