View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Convert String to int in Java: Methods and Examples

Updated on 13/05/20255,654 Views

Introduction

In Java programming, converting data from one type to another is a basic yet essential skill. One of the most common conversions you'll encounter is turning a String into an int. For example, user inputs, file data, or API responses often come as Strings—even if they represent numbers.

Converting these Strings to integers allows you to perform calculations, comparisons, and logic-based operations with ease. Java offers several methods to make this conversion straightforward and reliable, each suited for different use cases.

In this blog, we’ll explain various ways to convert a String to an int in Java, complete with working code examples and solutions to common errors.

Online software engineering courses can be a smart next step for gaining a stronger grasp of Java fundamentals and best practices.

Understanding Java Data Types: String and int

Before diving into conversion methods, let's quickly understand the two data types we're working with:

  • String: A reference type in Java that represents a sequence of characters
  • int: A primitive data type in Java that represents 32-bit integer values

Converting between these types is necessary because:

  1. User input often comes as String values
  2. Data from external sources (files, databases, web services) is typically in String format
  3. Many algorithms and calculations require numeric types

Methods on How to Convert String to int in Java

Let’s see several ways on how to convert String to int in Java programming. Each approach has its advantages and specific use cases.

Method 1: Using Integer.parseInt()

The most common and straightforward method for string to int conversion in Java is using the parseInt() method from the Integer class.

Syntax:

int value = Integer.parseInt(string);

Example 1: Basic String to int Conversion

public class StringToIntExample {
    public static void main(String[] args) {
        // String containing a numeric value
        String numberStr = "123";
        
        // Convert String to int using parseInt
        int number = Integer.parseInt(numberStr);
        
        // Verify the conversion
        System.out.println("String value: " + numberStr);
        System.out.println("Integer value: " + number);
        System.out.println("Integer value + 7: " + (number + 7));
    }
}

Output:

String value: 123

Integer value: 123

Integer value + 7: 130

This example successfully converts the string "123" to the integer value 123. The addition operation confirms that we're working with a numeric type.

Stay ahead with these handpicked, high-impact courses.

Method 2: Using Integer.valueOf()

Another approach is to use the valueOf() method, which returns an Integer object rather than a primitive int.

Syntax:

int value = Integer.valueOf(string);

Example 2: Using valueOf() for Conversion

public class StringToIntValueOf {
    public static void main(String[] args) {
        // String containing a numeric value
        String numberStr = "456";
        
        // Convert String to Integer object first
        Integer integerObj = Integer.valueOf(numberStr);
        
        // Get the primitive int value
        int number = integerObj.intValue();
        
        // Alternatively, use auto-unboxing
        int numberDirect = Integer.valueOf(numberStr);
        
        System.out.println("String value: " + numberStr);
        System.out.println("Integer object value: " + integerObj);
        System.out.println("Primitive int value: " + number);
        System.out.println("Direct conversion with auto-unboxing: " + numberDirect);
    }
}

Output:

String value: 456

Integer object value: 456

Primitive int value: 456

Direct conversion with auto-unboxing: 456

This example demonstrates how to use valueOf() to first get an Integer object, and then extract the primitive int. Thanks to auto-unboxing in modern Java, you can also directly assign the Integer object to an int variable.

Difference Between parseInt() and valueOf()

While both methods accomplish string to int conversion, there are some differences:

Feature

parseInt()

valueOf()

Return type

primitive int

Integer object

Memory efficiency

More efficient for primitive operations

Less efficient due to object creation

Caching

No caching

Caches small values (-128 to 127)

Usage in generics

Cannot be used directly with generic types

Can be used with generic types

Performance

Slightly better for primitive operations

Slightly worse due to boxing/unboxing

Method 3: Using Scanner Class

For parsing input from various sources, the Scanner class provides convenient methods for string to int conversion.

Example 3: Using Scanner for String to int Conversion

import java.util.Scanner;

public class StringToIntScanner {
    public static void main(String[] args) {
        // String containing a numeric value
        String input = "789";
        
        // Create a Scanner from the String
        Scanner scanner = new Scanner(input);
        
        // Check if the next token is an integer
        if (scanner.hasNextInt()) {
            int number = scanner.nextInt();
            System.out.println("Converted value: " + number);
        } else {
            System.out.println("Input is not a valid integer");
        }
        
        // Close the scanner
        scanner.close();
    }
}

Output:

Converted value: 789

This approach is particularly useful when reading from input streams or when you need to validate if the string contains a valid integer before attempting conversion.

Advanced Examples of How to Convert String to Int in Java

Let's explore some more complex scenarios for string to int conversion in Java.

Converting String with Different Radix (Base)

The parseInt() and valueOf() methods support an optional radix parameter to specify the numeral system (base) of the input string.

Example 4: Converting Strings with Different Bases

public class StringToIntRadix {
    public static void main(String[] args) {
        // Binary (base 2) string
        String binaryStr = "1010";
        int binaryToDecimal = Integer.parseInt(binaryStr, 2);
        System.out.println("Binary " + binaryStr + " to decimal: " + binaryToDecimal);
        
        // Octal (base 8) string
        String octalStr = "77";
        int octalToDecimal = Integer.parseInt(octalStr, 8);
        System.out.println("Octal " + octalStr + " to decimal: " + octalToDecimal);
        
        // Hexadecimal (base 16) string
        String hexStr = "1A";
        int hexToDecimal = Integer.parseInt(hexStr, 16);
        System.out.println("Hexadecimal " + hexStr + " to decimal: " + hexToDecimal);
        
        // Custom base (e.g., base 5)
        String base5Str = "431";
        int base5ToDecimal = Integer.parseInt(base5Str, 5);
        System.out.println("Base-5 " + base5Str + " to decimal: " + base5ToDecimal);
    }
}

Output:

Binary 1010 to decimal: 10

Octal 77 to decimal: 63

Hexadecimal 1A to decimal: 26

Base-5 431 to decimal: 116

This example demonstrates how to convert strings representing numbers in different numeral systems to decimal integers.

Handling Exceptions in String to int Conversion

String to int conversion can throw a NumberFormatException if the string doesn't represent a valid integer. It's important to handle this exception properly.

Example 5: Handling NumberFormatException

public class StringToIntExceptionHandling {
    public static void main(String[] args) {
        // Array of strings to convert
        String[] inputs = {"123", "456", "abc", "123f", "-789", "  42  "};
        
        for (String input : inputs) {
            try {
                int number = Integer.parseInt(input.trim());
                System.out.println("Successfully converted '" + input + "' to: " + number);
            } catch (NumberFormatException e) {
                System.out.println("Failed to convert '" + input + "': Not a valid integer");
            }
        }
    }
}

Output:

Successfully converted '123' to: 123

Successfully converted '456' to: 456

Failed to convert 'abc': Not a valid integer

Failed to convert '123f': Not a valid integer

Successfully converted '-789' to: -789

Successfully converted '  42  ' to: 42

This example demonstrates proper exception handling when converting various strings to integers. Notice that we also use the trim() method to remove leading and trailing whitespace.

How to Convert int to String in Java

Often, you'll also need to perform the reverse operation: converting an int to a String. Let's cover the main methods for completeness.

Method 1: Using String.valueOf()

The most straightforward approach is to use the valueOf() method from the String class.

Example 6: Using String.valueOf() for int to String Conversion

public class IntToStringValueOf {
    public static void main(String[] args) {
        // Integer values to convert
        int number1 = 123;
        int number2 = -456;
        
        // Convert int to String using String.valueOf()
        String str1 = String.valueOf(number1);
        String str2 = String.valueOf(number2);
        
        // Verify the conversion
        System.out.println("Original int: " + number1 + ", Converted String: " + str1);
        System.out.println("Original int: " + number2 + ", Converted String: " + str2);
        
        // Demonstrating that we have strings (concatenation)
        System.out.println("Concatenation test: " + str1 + str2);
    }
}

Output:

Original int: 123, Converted String: 123

Original int: -456, Converted String: -456

Concatenation test: 123-456

Method 2: Using Integer.toString()

Another approach is to use the toString() method from the Integer class.

Example 7: Using Integer.toString() for int to String Conversion

public class IntToStringToString {
    public static void main(String[] args) {
        // Integer value to convert
        int number = 789;
        
        // Convert int to String using Integer.toString()
        String str = Integer.toString(number);
        
        // Verify the conversion
        System.out.println("Original int: " + number + ", Converted String: " + str);
        
        // Converting with different radix (base)
        String binaryStr = Integer.toString(number, 2);
        String hexStr = Integer.toString(number, 16);
        
        System.out.println("Number " + number + " in binary: " + binaryStr);
        System.out.println("Number " + number + " in hexadecimal: " + hexStr);
    }
}

Output:

Original int: 789, Converted String: 789

Number 789 in binary: 1100010101

Number 789 in hexadecimal: 315

This example also shows how to convert integers to strings in different number systems by specifying the radix parameter.

Method 3: String Concatenation

The simplest (though not always the most efficient) way to convert int to String is using string concatenation with an empty string.

Example 8: Using String Concatenation for int to String Conversion

public class IntToStringConcatenation {
    public static void main(String[] args) {
        // Integer value to convert
        int number = 42;
        
        // Convert int to String using concatenation with empty string
        String str = "" + number;
        
        // Verify the conversion
        System.out.println("Original int: " + number + ", Converted String: " + str);
        
        // Demonstrate string operations
        System.out.println("Length of the string: " + str.length());
        System.out.println("First character: " + str.charAt(0));
    }
}

Output:

Original int: 42, Converted String: 42

Length of the string: 2

First character: 4

This method is simple but less efficient than using String.valueOf() or Integer.toString() because it creates more temporary objects.

Common Pitfalls and How to Avoid Them

When converting between String and int in Java, be aware of these common issues:

1. Handling Non-Numeric Strings

Always validate input or use proper exception handling when converting strings that might not be valid integers.

public static Integer safeParseInt(String str) {
    try {
        return Integer.parseInt(str);
    } catch (NumberFormatException e) {
        return null; // or a default value
    }
}

2. Dealing with Leading/Trailing Whitespace

Remember to trim strings before conversion to avoid NumberFormatException:

String input = "  123  ";
int number = Integer.parseInt(input.trim());

3. Number Format Localization

The standard conversion methods don't handle locale-specific number formats like thousands separators:

String localizedNumber = "1,234,567";
// This will fail with NumberFormatException:
// int number = Integer.parseInt(localizedNumber);

// Correct approach using NumberFormat:
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

try {
    Number parsedNumber = NumberFormat.getNumberInstance(Locale.US).parse(localizedNumber);
    int number = parsedNumber.intValue();
    System.out.println("Parsed number: " + number);
} catch (ParseException e) {
    System.out.println("Failed to parse localized number");
}

4. Integer Overflow

Be cautious when parsing strings that might represent numbers outside the int range (-2,147,483,648 to 2,147,483,647):

public static void checkIntegerOverflow(String str) {
    try {
        int number = Integer.parseInt(str);
        System.out.println("Parsed as int: " + number);
    } catch (NumberFormatException e) {
        try {
            long longValue = Long.parseLong(str);
            System.out.println("Number too large for int, parsed as long: " + longValue);
        } catch (NumberFormatException e2) {
            System.out.println("Not a valid number");
        }
    }
}

Performance Considerations

When choosing a method for string to int conversion, consider these performance aspects:

  1. parseInt() vs valueOf(): For primitive int, parseInt() is slightly more efficient since valueOf() creates an Integer object
  2. Frequency of Conversion: In performance-critical code with frequent conversions, avoiding unnecessary object creation matters
  3. valueOf() Caching: valueOf() caches Integer objects for values from -128 to 127, providing better performance for these small values
  4. String Concatenation: Using string concatenation ("" + number) for int to String conversion is generally less efficient

Best Practices for String-int Conversions in Java

To ensure reliable and maintainable code when working with String to int conversions:

  1. Always validate input before attempting conversion
  2. Handle exceptions appropriately using try-catch blocks
  3. Use proper methods for performance: parseInt() for primitive ints, valueOf() for Integer objects
  4. Consider overflow when working with potentially large numbers
  5. Trim input strings to handle whitespace
  6. Document your assumptions about the format of input strings
  7. Use appropriate validation for user input to prevent conversion errors
  8. Consider locale when working with formatted numbers
  9. Test edge cases including minimum and maximum int values, zero, and negative numbers
  10. Choose the right conversion method based on your specific needs and performance requirements

Conclusion

Converting string to int in Java is a fundamental operation that's essential for many programming tasks. With methods like Integer.parseInt(), Integer.valueOf(), and proper exception handling, you can safely and efficiently convert between these data types in your applications.

Remember to consider the specific requirements of your application when choosing a conversion method, and always handle potential exceptions to create reliable code. Whether you're processing user input, working with files, or building database queries, mastering string to int conversion will make your Java code more effective and error-resistant.

FAQ

1. How do I convert a String to an int in Java?

You can convert a String to an int in Java using Integer.parseInt(string) or Integer.valueOf(string). The parseInt() method returns a primitive int, while valueOf() returns an Integer object which can be auto-unboxed to int.

2. What happens if I try to convert a non-numeric String to an int?

If you try to convert a non-numeric String to an int using parseInt() or valueOf(), Java will throw a NumberFormatException. Always use exception handling when converting user input or data from external sources.

3. How can I convert a String with decimal places to an integer?

To convert a String with decimal places to an int, you have two options: First parse it as a double and then cast to int (which truncates the decimal part), or parse it as a double and use Math.round() to round to the nearest integer:

String decimalStr = "123.45";
int truncated = (int) Double.parseDouble(decimalStr);  // 123
int rounded = (int) Math.round(Double.parseDouble(decimalStr));  // 123

4. Can I convert hexadecimal or binary Strings to int?

Yes, both parseInt() and valueOf() accept a second parameter for the radix (base). For hexadecimal (base 16), use Integer.parseInt(hexString, 16). For binary (base 2), use Integer.parseInt(binaryString, 2).

5. How do I handle potential NumberFormatException when converting String to int?

Always wrap your conversion code in a try-catch block to handle potential exceptions:

try {
    int number = Integer.parseInt(stringValue);
    // Process the number
} catch (NumberFormatException e) {
    // Handle the exception (log error, provide default value, etc.)
}

6. What's the difference between parseInt() and valueOf() for String to int conversion?

The main difference is that parseInt() returns a primitive int, while valueOf() returns an Integer object. In terms of functionality, valueOf() internally calls parseInt() and wraps the result in an Integer object. For caching, valueOf() caches Integer objects for values between -128 and 127.

7. How do I convert a String with thousands separators (like "1,000") to an int?

The standard parseInt() and valueOf() methods don't handle thousands separators. You need to either remove the separators first or use NumberFormat:

String numWithSeparator = "1,234,567";
String cleanNum = numWithSeparator.replace(",", "");
int number = Integer.parseInt(cleanNum);

8. What's the most efficient way to convert int to String?

The most efficient methods are String.valueOf(int) and Integer.toString(int). Avoid using string concatenation ("" + number) in performance-critical code as it creates more temporary objects.

9. How can I parse a String containing an int value that might be outside the int range?

If the String might represent a value outside the int range (-2,147,483,648 to 2,147,483,647), use Long.parseLong() or BigInteger.parse() to avoid overflow issues:

String largeNumberStr = "9999999999";
try {
    long longValue = Long.parseLong(largeNumberStr);
    System.out.println("As long: " + longValue);
} catch (NumberFormatException e) {
    System.out.println("Number too large even for long type");
}

10. How to convert int to String in Java with leading zeros?

You can use String.format() to create a string with leading zeros:

int number = 42;
String withLeadingZeros = String.format("%05d", number);  // "00042"

11. How can I convert a String containing a number in scientific notation to an int?

First parse it as a double to handle the scientific notation, then convert to int:

String scientific = "1.23E2";  // 123 in scientific notation
int number = (int) Double.parseDouble(scientific);
image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.