Search for Hubs, Articles and Topics
Search for Hubs, Articles and Topics

Convert String to Int in Java

Learn about Convert String to Int in Java

11 Jul 2021-5 mins read

You are in your computer lab trying to formulate a complex Java equation that will surely be a boon to mankind. Variables are racing in your head and equations are wandering. You are very close to the solution and require a multiplication to a string. All you want to do is convert a string to int, multiply the value and submit your equation. The thought of being stuck at the endpoint made you search the web and you came across the article/blog/post to change string to integer in java.

This post/article/blog will take you through two methods of converting a string to an integer:

  1. Integer.parseInt()
  2. Integer.valueOf()

which will help you choose a method suitable for your program. The post will go through syntax, functions, exceptions, and errors to foolproof your winning strategy.

Convert String to Integer in Java

Integer.parseInt() – Converts String to int

Ever wondered about dividing two strings or adding a numerical value to a string?

That wouldn’t be a good idea unless we convert a string to an integer. The parseInt() method in java converts a string to a primitive (basic) data type, i.e., int. If your goal is to convert a string to its binary, octal, or hexadecimal equivalent, choose your radix argument accordingly and the function will convert string to int in java.

Syntax:

For single argument -> parseInt(String s)
For two arguments -> parseInt(String s, int radix)

Example:

String str = ‘5678’;
int change = Integer.parseInt(str);

Code:

class scalerAcademy {
    public static void main ( String args [] ) {
        String str = "789"; // creating a string literal
        int ans = Integer.parseInt(str); // passing the value of string in ans
        int ans1 = Integer.parseInt(str,16); // passing the value of radix as an int
       
        System.out.println(ans); // outputs 789
        System.out.println(ans1); // outputs 1929
    }
}

Explanation: For a single argument, the function will convert a string to int in java whereas, for two arguments, the radix number converts a string to decimal, binary, or hexadecimal equivalent.

Convert string to int in java

Integer.valueOf() – Converts String to int

‘Why do we have another function to convert string to integer?’

This question would be racing in most of the minds. The function returns the integer object when an argument is passed. It takes in the string or an integer as a first argument and converts it into an object. This works the same as parseInt() and changes a string to integer in java for the radix argument.

Syntax:

For single argument -> valueOf(String s)
For two arguments -> valueOf(String s, int radix)

Example:

String str = ‘12345’;
Integer change = Integer.valueOf(str);

Code:

class scalerAcademy {
    public static void main ( String args [] ) {
        String str = "789"; // creating a string
        Integer ans = Integer.valueOf(str); // passing the value to an Integer class
        Integer ans1 = Integer.valueOf(str,16); // passing radix value as int
       
        System.out.println(ans); //outputs 789
        System.out.println(ans1); // outputs 1929
    }
}

Explanation: The radix argument returns the hexadecimal equivalent of the number ‘789’.

Convert string to integer java

What if we passed a data type other than an int in parseInt() or valueOf()?

The program will throw a NumberFormatException upon passing values other than numerics. An empty or null string is also liable for the same error and would not convert a string to an integer in java.

Code:

class scalerAcademy {
    public static void main ( String args [] ) {
        String str = " "; // creating an empty string
        String name = "I love Interview Bit"; // creating a character string
       
        int ans = Integer.parseInt(str); // passing empty string
        int ans1 = Integer.parseInt(name); // passing character string
       
        System.out.println(ans + "\n"); // throws NumberFormatException
        System.out.println(ans1); // throws NumberFormatException
    }
}

Explanation: The above code will show a runtime exception upon execution.

Remember/Pain Points:

  • The presence of leading zeroes in the string will not be counted by the parseInt() as well as the valueOf() method.
  • The first character as ‘+’ or ‘-’ indicates the sign of the number which is accepted by both methods of changing the string to integer in java.

Code:

class scalerAcademy {
    public static void main ( String args [] ) {
        String leadingZero = "00789"; // string with leading zeroes
        String signConvert = "-12"; // string with a sign
       
        int ans = Integer.parseInt(leadingZero); 
        int ans1 = Integer.parseInt(signConvert);
       
        System.out.println(ans + "\n"); // outputs 789
        System.out.println(ans1); // outputs -12
    }
}

Explanation: The program illustrates the acceptance of a sign and scrapping of leading zeroes when we tried to convert a string to int in java.

String to int conversion with Leading Zeroes

There could be a case where leading zeroes are necessary for your program. To retain leading zeroes in a string, opt-in for the format() method to convert a string to int in java using parseInt() or valueOf() method.

Example:

String str = ‘00289’;
str = String.format(“%05d”, Integer.parseInt(str));

Quick Recall

  • parseInt() will convert string to an int whereas valueOf() will convert string to an object of Integer class
  • Null, empty, or non-numeric data in a string will throw a NumberFormatException
  • format() method works best for retaining leading zeroes
  • Beware of multiple arguments when modifying string to integer in Java