The Basic Method: Using Integer.parseInt()

To convert a string to an integer in Java, use the Integer.parseInt() method. This is the most direct approach and works when your string contains only digits, optionally with a minus sign at the start.

Here is how it works in practice:

String myString = "42"; int myNumber = Integer.parseInt(myString); System.out.println(myNumber); // Output: 42

The method reads the string character by character and converts it to an integer value. If the string is "42", you get the integer 42. If the string is "-15", you get the integer -15.

Key Takeaways

  • Integer.parseInt() is the standard method for converting a string to an int, and it works with negative numbers as long as the minus sign comes first.
  • If your string contains non-numeric characters or is empty, Integer.parseInt() will throw a NumberFormatException and stop your program unless you catch it.
  • Use a try-catch block to handle strings that might not be valid numbers, so your program does not crash.
  • Integer.valueOf() is an alternative that returns an Integer object instead of a primitive int, but both methods convert the same way.
  • Always check your string for leading or trailing spaces, because parseInt() will reject them — use .trim() to remove them first.

Handling Invalid Strings with Try-Catch

If you try to convert a string that is not a valid number, Integer.parseInt() throws a NumberFormatException. Your program will crash unless you catch this exception.

Wrap the conversion in a try-catch block to handle this safely:

String userInput = "hello"; try {   int myNumber = Integer.parseInt(userInput);   System.out.println(myNumber); } catch (NumberFormatException e) {   System.out.println("That is not a valid number"); }

When the string "hello" reaches parseInt(), the catch block runs instead, and your program prints the error message and continues. Without the try-catch, the program would stop.

Removing Spaces Before Converting

Strings sometimes have spaces at the beginning or end — especially if they come from user input or a text file. Integer.parseInt() will reject these strings and throw an exception.

Use the .trim() method to remove leading and trailing spaces before converting:

String userInput = " 42 "; int myNumber = Integer.parseInt(userInput.trim()); System.out.println(myNumber); // Output: 42

The .trim() method removes all whitespace from both ends of the string. After trimming, " 42 " becomes "42", and parseInt() can convert it successfully. This is especially useful when reading strings from a keyboard, a file, or a web form.

Using Integer.valueOf() as an Alternative

Another method is Integer.valueOf(), which converts a string to an Integer object rather than a primitive int. For most purposes, the two work the same way:

String myString = "42"; Integer myNumber = Integer.valueOf(myString); System.out.println(myNumber); // Output: 42

The difference is that Integer.valueOf() returns an Integer object, while parseInt() returns a primitive int. In practice, Java automatically converts between them in most situations, so you can use either one. Integer.valueOf() also throws NumberFormatException for invalid strings, so you still need a try-catch block if the string might be invalid.

Use Integer.valueOf() if you need to store the value in a collection like an ArrayList, or if you need to call methods on the number. Use parseInt() if you just need a straightforward integer value for math or comparison.

Converting Strings in Different Number Bases

By default, parseInt() assumes your string is in base 10 (decimal). If your string represents a number in a different base — such as hexadecimal (base 16) or binary (base 2) — you can specify the base as a second argument:

String hexString = "1A"; int myNumber = Integer.parseInt(hexString, 16); System.out.println(myNumber); // Output: 26

In this example, "1A" in hexadecimal equals 26 in decimal. The second argument tells parseInt() which base to use. Common bases are 2 (binary), 8 (octal), 10 (decimal), and 16 (hexadecimal).

If you do not specify a base, parseInt() assumes base 10. If you specify the wrong base for your string, you will get a NumberFormatException.

What Happens with Very Large Numbers

An int in Java can hold values from -2,147,483,648 to 2,147,483,647. If your string represents a number larger than this range, Integer.parseInt() will throw a NumberFormatException.

If you need to convert very large numbers, use Long.parseLong() instead, which handles values up to 9,223,372,036,854,775,807:

String largeNumber = "9999999999"; long myNumber = Long.parseLong(largeNumber); System.out.println(myNumber); // Output: 9999999999

Long.parseLong() works exactly like Integer.parseInt(), but it returns a long instead of an int. Use it when your string might represent a number too large for an int to hold.

Frequently Asked Questions

What is the difference between parseInt and valueOf?

parseInt() returns a primitive int, while valueOf() returns an Integer object. Both convert the string the same way and throw the same exception for invalid input. Use parseInt() for straightforward conversions and valueOf() when you need an object — for example, to store in a collection or to call methods on it.

Why does my string with spaces not convert?

Integer.parseInt() rejects strings with leading or trailing spaces. Use .trim() before parsing: Integer.parseInt(myString.trim()). This removes all whitespace from both ends of the string.

Can I convert a decimal string like "3.14" to an int?

No, Integer.parseInt() will throw a NumberFormatException because it only accepts whole numbers. If you need to convert "3.14", use Double.parseDouble() first, then cast it to an int: int myNumber = (int) Double.parseDouble("3.14");. This gives you 3, dropping the decimal part.

What should I do if the string might not be a valid number?

Always use a try-catch block to handle NumberFormatException. Wrap the parseInt() call in try, and in the catch block, handle the error — print a message, use a default value, or ask the user to try again.

Can I convert strings in hexadecimal or binary?

Yes, use the two-argument version of parseInt(). For hexadecimal: Integer.parseInt(myString, 16). For binary: Integer.parseInt(myString, 2). The second argument specifies the base of the number system your string uses.