To convert a String to an int in Java, use Integer.parseInt() for a primitive int or Integer.valueOf() for an Integer object.

  • Integer.parseInt(String s):

    • Returns a primitive int.

    • Throws a NumberFormatException if the string is invalid (e.g., contains non-numeric characters, is empty, or is null).

    • Example:

      String str = "123";
      int num = Integer.parseInt(str);
      System.out.println(num); // Output: 123
  • Integer.valueOf(String s):

    • Returns an Integer object (wrapper class).

    • Also throws NumberFormatException for invalid inputs.

    • Useful when working with collections like ArrayList<Integer>.

    • Internally uses parseInt().

Always handle exceptions when converting strings to integers to avoid runtime crashes:

String str = "123x";
try {
    int num = Integer.parseInt(str);
    System.out.println("Converted: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid number format: " + str);
}

Best Practice: Use Integer.parseInt() for primitive int and wrap it in a try-catch block to handle invalid inputs safely.
❌ Avoid using the deprecated Integer(String s) constructor.

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)
Answer from Bozho on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › different-ways-for-integer-to-string-conversions-in-java
Java Convert int to String | How to Convert an Integer into a String - GeeksforGeeks
April 9, 2025 - Note: This method is not efficient as an instance of the Integer class is created before conversion is performed. And deprecated and marked as removal. Here, we will declare an empty string and using the '+' operator, we will simply store the resultant as a string. Now by this, we are successfully able to append and concatenate these strings. ... // Java Program to Illustrate Integer to String Conversions // Using Concatenation with Empty String class Geeks { // Main driver method public static void main(String args[]) { // Custom integer values int a = 1234; int b = -1234; // Concatenating with empty strings String str1 = "" + a; String str2 = "" + b; // Printing the concatenated strings System.out.println("String str1 = " + str1); System.out.println("String str2 = " + str2); } }
Discussions

Java convert an Int to a String | Go4Expert
Discussion in 'Java' started by tombezlar, Mar 24, 2021. More on go4expert.com
🌐 go4expert.com
March 24, 2021
Converting a Number to a String
The docs will answer that question quite clearly https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toString(int) https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(int) under the String.valueOf(int) description: The representation is exactly the one returned by the Integer.toString method of one argument. to make it even more clear if we look at the source code for String.valueOf(int) https://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java we find that it literally just calls Integer.toString(int) public static String valueOf(int i) { return Integer.toString(i); } More on reddit.com
🌐 r/javahelp
3
6
August 14, 2022
how to convert int to string
Joel Velez is having issues with: I don't know why it is giving me compile errors. ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
April 13, 2015
JAVA: How to turn stringbuilder to Int.
Integer.parseInt() is correct. It takes a string and changes it into an int. You can trivially get a string from a stringBuilder by just using the toString method. More on reddit.com
🌐 r/learnprogramming
2
1
November 5, 2017
People also ask

Q1. Why do we need to convert a string to an int in Java?
We often need to convert a string to an int while working with user inputs, reading data from files, or APIs where numerical data is stored in text format.
🌐
intellipaat.com
intellipaat.com › home › blog › string to integer java
How to Convert String to Integer in Java?
Q3. How to convert a string to an integer without using any direct method in Java?
To convert a string to an integer without using any direct method, iterate through each character, subtract ‘0’ to get the numeric value, and build the number using multiplication and addition.
🌐
intellipaat.com
intellipaat.com › home › blog › string to integer java
How to Convert String to Integer in Java?
Q2. What is the difference between Integer.valueOf() and Integer.parseInt()?
The major difference between Integer.valueOf() and Integer.parseInt() is that valueOf() returns an Integer object (wrapper class), while parseInt() returns a primitive int.
🌐
intellipaat.com
intellipaat.com › home › blog › string to integer java
How to Convert String to Integer in Java?
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-string-to-int-in-java
String to int in Java - GeeksforGeeks
The most common method to convert a string to a primitive int is Integer.parseInt(). It throws a NumberFormatException if the string contains non-numeric characters. ... // Java Program to demonstrate // String to int conversion using parseInt() ...
Published   July 23, 2025
🌐
Great Learning
mygreatlearning.com › blog › it/software development › 4 useful methods to convert java int to string with examples
4 Useful Methods to Convert Java Int to String with Examples
July 28, 2025 - Just add + to empty string and int or any number will be converted to String. Shortcut method but does the job for sure. For simple cases - yes, it works: If you're just looking for quick things like logging a value or debugging, the "" + number ...
🌐
Go4Expert
go4expert.com › forums › java-convert-int-string-t35421
Java convert an Int to a String | Go4Expert
March 24, 2021 - Here are 3 ways to convert an int to a String String s = String.valueOf(n); String s = Integer.toString(n); String s = "" + n; I understand what we...
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › java › how do i convert a string to an int in java?
How do I convert a String to an int in Java? | Sentry
If you need to store the result in a database, then Integer is nullable which might be useful. Integer includes other helper methods, which you might need if you do further processing after the conversion. The primitive int can behave more predictably and manipulating int variables sometimes requires less code. ... class Main { public static void main(String[] args) { String s1 = "1000"; String s2 = "1000"; Integer n1 = Integer.valueOf(s1); Integer n2 = Integer.valueOf(s2); System.out.println("n1 == n2: " + String.valueOf(n1 == n2)); } }
🌐
Oracle
docs.oracle.com › en › java › javase › 20 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 20 & JDK 20)
July 10, 2023 - The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
🌐
Udemy
blog.udemy.com › home › how to convert integers to strings in java
How to Convert Integers to Strings in Java - Udemy Blog
December 4, 2019 - int abc=10; double bcd=12.23; //String declaration String abc=“”Hello”; StringBuffer str1=new StringBuffer(”Hello World”); Numeric values are used for performing calculation and manipulations. Every data type in Java has a size limit and value range. Want to know about core Java concepts?
🌐
Java67
java67.com › 2015 › 08 › 2-ways-to-parse-string-to-int-in-java.html
2 ways to parse String to int in Java - Example Tutorial | Java67
So every time you pass a numeric String which is in the range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but returns the same value from the cached pool. The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like the parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to an int value in Java.
🌐
Baeldung
baeldung.com › home › java › java array › converting a string array into an int array in java
Converting a String Array Into an int Array in Java | Baeldung
January 8, 2024 - In this article, we’ve learned two ways to convert a string array to an integer array through examples. Moreover, we’ve discussed handling the conversion when the string array contains invalid number formats. If our Java version is 8 or later, the Stream API would be the most straightforward ...
🌐
Reddit
reddit.com › r/javahelp › converting a number to a string
r/javahelp on Reddit: Converting a Number to a String
August 14, 2022 -

Hey, all. I was working on some Codewars fundamentals and I came across this problem. My solution was accepted and, on the list of acceptable solutions, I see what seems to be an equally useful solution. I just wondered if there's any reason to use one over the other in any particular situation or if they do the same thing all the time. The passed in variable was some integer num.

My solution was:

return Integer.toString(num);

The other solution I saw was:

return String.valueOf(num);

Any insight would be much appreciated. Thanks!

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 8 )
October 20, 2025 - The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
🌐
Educative
educative.io › answers › how-to-convert-an-integer-to-a-string-in-java
How to convert an integer to a string in Java
The first argument is any string containing %d. The second argument is the integer you want to convert. This method will replace %d with your integer.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-convert-integer-to-string-in-java
Int to String in Java – How to Convert an Integer into a String
January 5, 2023 - You can convert variables from one data type to another in Java using different methods. In this article, you'll learn how to convert integers to strings in Java in the following ways: Using the Integer.toString() method. Using the String.valueOf(...
🌐
Team Treehouse
teamtreehouse.com › community › how-to-convert-int-to-string
how to convert int to string (Example) | Treehouse Community
April 13, 2015 - Use the class Integer.toString function. This will parse the integer and return a static string. https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html · 5,969 Points · Ivan Sued · 5,969 Points April 13, 2015 9:09pm · I think the ...
Top answer
1 of 5
7

Things I like about your code

  • The idea to calculate the length of a number with the logarithm is really good!
  • In my opinion you are writing good comments.
  • Good variable names
  • Works as intended, without (to my knowledge) any bugs.

Criticism

returnDigitString()

  • It is considered bad practice to put more than one command into one line. So please make line breaks after every ";".
  • Your solution is pretty long (over 30 lines) in comparison to the complexity of the problem. You could also have done something like that:
    public static String returnDigitString(int digit) {
        String res = "";
        String[] digits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        for(int i = 0; i <= 9; i++) {
            if(digit == i) {
                res += digits[i];
                break;
            }
        }
        return res;
    }

main()

  • You are not using the array "reverseStr". The String "digits" is not used either.
  • When I started your program the first time, I didn't know what to do, because your program didn't tell me. Before scanning a user input, I would tell the user to input something.
System.out.println("Please enter number:");
Scanner scn = new Scanner(System.in);
int number = scn.nextInt();

If you want to improve this point even further (which is highly recommended!), you can use something like that (you will have to use import java.util.InputMismatchException;):

System.out.println("Please enter number:");
Scanner scn = new Scanner(System.in);
int number;
while(true) {
    try {
        number = scn.nextInt();
        break;
    }
    catch(InputMismatchException e) {
        System.out.println("That's not a number!");
        scn.nextLine();
    }
}

This will check, whether the user really enters a number. If the user enters something else, the program will ask him again to enter a number.

  • Something like that is considered bad practice:
if(number != 0) {
length = ( int ) (Math.log10(number) + 1 );}

Please write

if(number != 0) {
        length = (int) (Math.log10(number) + 1);
}

instead.

  • "valStr" is not necessary. You can just write:
strSeq = returnDigitString(remainder) + strSeq;

But this really is a minor point and just my personal opinion. It's fine to use an extra variable for this.

Codestructure

  • I would use an extra method for the content of the main-method. Just use the main-method to call the new method.
2 of 5
9

Personally I think your algorithm has been made a lot more complex than needed.

Is the concatenation a requirement? If not, you can simplify by directly converting each digit into a char and storing it in a char[]. This way instead of inefficiently concatenating each digit onto the string, you can use the string constructor overload that takes a char[].

With this simplification, the method can be reduced to just a few lines:

  public static String intToString(int num) {
    if(num == 0){
      return "0";
    }
    int count = 0;
    boolean isNeg = false;
    if (num < 0) {
      num *= -1;
      count = 1;
      isNeg = true;
    }
    count += (int) Math.log10(num) + 1;
    char[] digits = new char[count];
    if (isNeg) {
      digits[0] = '-';
    }
    --count;
    while(num > 0) {
      digits[count--] = (char) ((num % 10) + '0');
      num /= 10;
    }
    return new String(digits);
  }
🌐
OpenReplay
blog.openreplay.com › convert-string-int-java
How to Convert a String to Int in Java
February 5, 2025 - Converting a string to an integer in Java is simple with methods like Integer.parseInt() and Integer.valueOf().
🌐
Tutorialspoint
tutorialspoint.com › java › number_parseint.htm
Java - parseInt() Method
... parseInt(int i) − This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
🌐
Intellipaat
intellipaat.com › home › blog › string to integer java
How to Convert String to Integer in Java?
July 22, 2025 - In this guide, you will learn how and when to use different methods to convert a string to int in Java with examples, and also know how to fix errors if the string is not valid.