String conversion
String to Int
Integer conversion
Programming
Type casting

How can I convert String to Int?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Converting text to an integer is a small task that often carries real edge cases: empty input, invalid characters, whitespace, or values that do not fit in range. The right answer depends on the language, but the pattern is always the same: parse carefully and decide what should happen when the text is not a valid integer.

Parsing in Common Languages

Different languages use different APIs, but the basic idea is consistent. Here are direct examples in several common languages.

Java

java
1public class ParseJava {
2    public static void main(String[] args) {
3        String text = "123";
4        int value = Integer.parseInt(text);
5        System.out.println(value);
6    }
7}

If the string is invalid, Java throws NumberFormatException.

Python

python
text = "123"
value = int(text)
print(value)

If parsing fails, Python raises ValueError.

JavaScript

javascript
const text = "123";
const value = Number.parseInt(text, 10);
console.log(value);

Passing the radix 10 is good practice because it makes the intent explicit.

C#

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        string text = "123";
8        int value = int.Parse(text);
9        Console.WriteLine(value);
10    }
11}

In C#, invalid input throws FormatException or OverflowException depending on the failure.

Prefer Safe Parsing When Input Is Untrusted

If the text comes from a user, file, or network request, exception-free parsing is often nicer than a try-catch around every input.

Example in Java:

java
1public class SafeJavaParse {
2    public static Integer tryParse(String text) {
3        try {
4            return Integer.parseInt(text.trim());
5        } catch (NumberFormatException ex) {
6            return null;
7        }
8    }
9
10    public static void main(String[] args) {
11        System.out.println(tryParse("42"));
12        System.out.println(tryParse("oops"));
13    }
14}

Example in C# using TryParse:

csharp
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        if (int.TryParse("42", out int value))
8        {
9            Console.WriteLine(value);
10        }
11        else
12        {
13            Console.WriteLine("invalid integer");
14        }
15    }
16}

That style is often better for validation-heavy code.

Whitespace, Signs, and Bases

Parsing can also involve rules beyond ordinary decimal numbers:

  • leading and trailing whitespace may need trimming
  • '-42 is valid in most integer parsers'
  • binary or hexadecimal text may need an explicit base

Example in Java for hexadecimal:

java
1public class HexParse {
2    public static void main(String[] args) {
3        int value = Integer.parseInt("FF", 16);
4        System.out.println(value);
5    }
6}

So if your text is not plain base-10 input, use the API that lets you specify the radix clearly.

Do Not Confuse Parsing with Casting

This is a common conceptual mistake. A cast changes how the compiler interprets a value that is already numeric. Parsing converts text into a numeric value. You cannot cast "123" to an integer in the same way you cast 3.14 to 3.

That distinction matters because parsing can fail due to content, while casting fails due to type rules.

Common Pitfalls

  • Using parsing APIs on untrusted input without validation or error handling.
  • Forgetting to trim whitespace when input comes from forms or files.
  • Ignoring overflow cases where the digits are valid but the number is too large.
  • Assuming parsing and casting are the same operation.
  • Forgetting to specify a radix when the input is not base 10.

Summary

  • Converting text to an integer means parsing, not casting.
  • Every language has a direct parse function such as Integer.parseInt, int(), parseInt, or int.Parse.
  • For untrusted input, safe parsing patterns are usually better than unchecked exceptions.
  • Trim input and handle invalid or out-of-range values explicitly.
  • Use radix-aware parsing when the input is hexadecimal, binary, or another non-decimal format.

Course illustration
Course illustration

All Rights Reserved.