Java Program to convert string type variables into int

Updated on December 16, 2024
Convert string type variables into int header image

Introduction

In Java, converting a string to an integer is a common operation, especially when dealing with data input where the numbers are received as text. This conversion allows numeric operations, such as arithmetic or logic checks, to be performed on data initially represented as strings.

In this article, you will learn how to convert string type variables into integers in Java. Utilize various methods, explore potential pitfalls like handling non-numeric strings, and learn best practices to ensure your conversions are safe and effective.

Basic Conversion Using Integer.parseInt()

Converting a Valid String to an Integer

  1. Start by defining a string that contains a valid integer.

  2. Use Integer.parseInt() to convert the string to an integer.

    java
    String numberStr = "123";
    int number = Integer.parseInt(numberStr);
    System.out.println(number);
    

    This code snippet takes a string numberStr and converts it to an integer number using Integer.parseInt(). Since "123" is a valid numeric string, this conversion will succeed and output the integer 123.

Handling Exceptions for Invalid Strings

  1. Prepare to handle cases where the string does not contain a valid integer.

  2. Use a try-catch block to catch NumberFormatException.

    java
    String invalidNumberStr = "abc";
    try {
        int number = Integer.parseInt(invalidNumberStr);
        System.out.println(number);
    } catch (NumberFormatException e) {
        System.out.println("Invalid string to convert: " + invalidNumberStr);
    }
    

    In this example, attempting to parse "abc" as an integer throws a NumberFormatException, which is caught and handled gracefully by displaying an error message.

Using Integer.valueOf()

Converting String to Integer

  1. Understand that Integer.valueOf() returns an instance of Integer rather than an int.

  2. Use Integer.valueOf() when you need an Integer object.

    java
    String numberStr = "456";
    Integer number = Integer.valueOf(numberStr);
    System.out.println(number);
    

    Here, numberStr is converted to an Integer object. This method is particularly useful when you need an object rather than a primitive type for collections or APIs requiring objects.

Difference Between parseInt() and valueOf()

  1. Recognize that both methods throw NumberFormatException for invalid inputs.

  2. Use parseInt() for int primitives and valueOf() for Integer objects.

    java
    // parseInt example
    int num1 = Integer.parseInt("789");
    
    // valueOf example
    Integer num2 = Integer.valueOf("789");
    
    System.out.println(num1);
    System.out.println(num2);
    

    Although these methods serve slightly different purposes, they behave the same way when faced with invalid inputs and can be used interchangeably depending on whether a primitive or an object is required.

Conclusion

Converting strings to integers in Java is straightforward but requires careful handling of potential exceptions, particularly with non-numeric strings. Whether using Integer.parseInt() for primitive int results or Integer.valueOf() for Integer objects, understanding the distinction and appropriate use cases ensures robust, error-free code. Implement these methods in your Java projects to handle numeric string conversions effectively and safely.