Convert String to Integer in Java

1. Introduction

Converting a string to an integer is a common requirement in Java programming, especially when dealing with numerical input from users, files, or networks. Java provides several ways to perform this conversion, primarily through Integer.parseInt() for primitive integers and Integer.valueOf() for Integer objects. This tutorial will demonstrate both methods.

Key Points

- Integer.parseInt(String s) converts a string to a primitive int.

- Integer.valueOf(String s) returns an Integer object.

- Both methods throw NumberFormatException if the string cannot be parsed as an integer.

2. Program Steps

1. Define a string that represents an integer value.

2. Convert the string to a primitive int using Integer.parseInt().

3. Convert the string to an Integer object using Integer.valueOf().

4. Print both converted values.

3. Code Program

public class StringToIntegerExample {
    public static void main(String[] args) {
        // String to be converted
        String integerString = "123";

        // Convert string to primitive int
        int intPrimitive = Integer.parseInt(integerString);

        // Convert string to Integer object
        Integer integerObject = Integer.valueOf(integerString);

        // Print the results
        System.out.println("Converted to primitive int: " + intPrimitive);
        System.out.println("Converted to Integer object: " + integerObject);
    }
}

Output:

Converted to primitive int: 123
Converted to Integer object: 123

Explanation:

1. String integerString = "123": Declares and initializes a string that contains a numerical value which can be converted to an integer.

2. int intPrimitive = Integer.parseInt(integerString): Converts the string to a primitive int using Integer.parseInt(). This method is straightforward and is used when an integer value is needed for calculations or logic operations.

3. Integer integerObject = Integer.valueOf(integerString): Converts the string to an Integer object using Integer.valueOf(). This method is useful when you need to use integers as objects, for instance in collections that do not support primitives.

4. System.out.println("Converted to primitive int: " + intPrimitive) and System.out.println("Converted to Integer object: " + integerObject): Prints both the primitive int and the Integer object to the console, confirming that the string has been successfully converted in both forms.


Comments