parseInt is the way to go. The Integer documentation says

Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.

parseInt is likely to cover a lot of edge cases that you haven't considered with your own code. It has been well tested in production by a lot of users.

Answer from ggovan on Stack Overflow
🌐
AWS
docs.aws.amazon.com › amazon mq › 開發人員指南 › 使用 amazon mq for rabbitmq › rabbitmq 教學 › 連接您的 jms 應用程式
連接您的 JMS 應用程式 - Amazon MQ
import jakarta.jms.*; import com.rabbitmq.jms.admin.*; // Setting the connection factory RMQConnectionFactory factory = new RMQConnectionFactory(); factory.setHost(envProps.getProperty("RABBITMQ_HOST", "localhost")); factory.setPort(Integer.parseInt(envProps.getProperty("RABBITMQ_PORT", "5672"))); factory.setUsername(envProps.getProperty("RABBITMQ_USERNAME", "guest")); factory.setPassword(envProps.getProperty("RABBITMQ_PASSWORD", "guest")); factory.setVirtualHost(envProps.getProperty("RABBITMQ_VIRTUAL_HOST", "/")); factory.useSslProtocol(); connection = factory.createConnection(); connection.s
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 8 )
October 20, 2025 - Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to ...
🌐
Tutorialspoint
tutorialspoint.com › home › java › java integer parsing
Java Integer Parsing
September 1, 2008 - 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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › integer-valueof-vs-integer-parseint-with-examples
Integer.valueOf() vs Integer.parseInt() with Examples - GeeksforGeeks
July 11, 2025 - Integer.valueOf() can take a character as parameter and will return its corresponding unicode value whereas Integer.parseInt() will produce an error on passing a character as parameter. ... // Program to test the method // when a character is passed as a parameter class Test3 { public static void main(String args[]) { char val = 'A'; try { // It can take char as a parameter int str1 = Integer.valueOf(val); System.out.print(str1); // It cannot take char as a parameter // Hence will throw an exception int str = Integer.parseInt(val); System.out.print(str); } catch (Exception e) { System.out.print(e); } } }
🌐
W3Schools
w3schools.com › jsref_parseint.asp
W3Schools.com
The parseInt() function parses a string and returns an integer.
🌐
PREP INSTA
prepinsta.com › home › tcs nqt › tcs nqt placement papers and questions 2026 › tcs nqt coding questions and answers 2026
TCS NQT Coding Questions and Answers 2026 | PrepInsta
1 week ago - import java.util.*; class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int no=sc.nextInt(); String bin=""; while(no!=0) { bin=(no&1)+bin; no=no>>1; } bin=bin.replaceAll("1","2"); bin=bin.replaceAll("0","1"); bin=bin.replaceAll("2","0"); int res=Integer.parseInt(bin,2); System.out.println(res); } } Python ·
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.parseint
Integer.ParseInt Method (Java.Lang) | Microsoft Learn
Parses the string argument as a signed integer in the radix specified by the second argument. [Android.Runtime.Register("parseInt", "(Ljava/lang/String;I)I", "")] public static int ParseInt(string s, int radix);
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › parseInt
parseInt() - JavaScript | MDN
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.
🌐
Tcsapps
codevita.tcsapps.com
TCS CodeVita | Home
sum += Integer.parseInt(str); } logger.debug(sum0); Given N number of x's, perform logic equivalent of the above Java code and print the output · First line contains an integer N · Second line will contain N numbers delimited by space · Number that is the output of the given code by taking inputs as specified above ·
🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java integer parseint method
Java Integer parseInt Method
September 1, 2008 - Explore the Java Integer parseInt method to convert strings into integers, featuring examples and usage tips.
🌐
Coderanch
coderanch.com › t › 377888 › java › intValue-ParseInt
intValue Vs ParseInt (Java in General forum at Coderanch)
September 21, 2005 - Integer.parseInt() is a static method, that you can use to parse a string into an int without the need to create an instance of class Integer.
🌐
Reddit
reddit.com › r/learnjava › integer.valueof() and parseint()
r/learnjava on Reddit: Integer.valueOf() and parseint()
September 14, 2023 -

Hello, i have started learning java recently by mooc. But during this course, it uses Integer.valueOf while taking integer inputs, I use same way but whenever i do it intellij suggests me parseint(). And I wonder if it is better to use parseint?

Top answer
1 of 3
9
Integer.parseInt() returns a primitive. valueOf() returns an Integer object. Call the one that matches the return type you need and avoid autoboxing/unboxing.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Scaler
scaler.com › home › topics › parseint() in java
parseInt() in Java - Scaler Topics
May 8, 2024 - It is used in Java for converting a string value to an integer by using the method parseInt().
🌐
YouTube
youtube.com › watch
parseInt Java Tutorial - String to Integer #56 - YouTube
$1,500 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE1500. See if you qualify for the JOB GUARANTEE! 👉 https://bit.ly/3HX970hThe parseIint java met...
Published   August 8, 2019
Top answer
1 of 8
47

Usually this is done like this:

  • init result with 0
  • for each character in string do this
    • result = result * 10
    • get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
    • add the digit to the result
  • return result

Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).

Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):

digit = ord(char) - ord('0')

For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:

digit = ord(char) - ord('0')
if digit > 9 then digit -= 7

Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.

One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.

2 of 8
28

The source code of the Java API is freely available. Here's the parseInt() method. It's rather long because it has to handle a lot of exceptional and corner cases.

public static int parseInt(String s, int radix) throws NumberFormatException {
    if (s == null) {
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) {
        throw new NumberFormatException("radix " + radix +
            " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {
        throw new NumberFormatException("radix " + radix +
            " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, max = s.length();
    int limit;
    int multmin;
    int digit;

    if (max > 0) {
        if (s.charAt(0) == '-') {
            negative = true;
            limit = Integer.MIN_VALUE;
            i++;
        } else {
            limit = -Integer.MAX_VALUE;
        }
        multmin = limit / radix;
        if (i < max) {
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            } else {
                result = -digit;
            }
        }
        while (i < max) {
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++), radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    if (negative) {
        if (i > 1) {
            return result;
        } else { /* Only got "-" */
            throw NumberFormatException.forInputString(s);
        }
    } else {
        return -result;
    }
}
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 21 & JDK 21)
January 20, 2026 - ... Deprecated, for removal: This API element is subject to removal in a future version. It is rarely appropriate to use this constructor. Use parseInt(String) to convert a string to a int primitive, or use valueOf(String) to convert a string to an Integer object.
🌐
Global Tech Council
globaltechcouncil.org › home › what is parseint in java?
What is parseInt in Java? - Global Tech Council
August 22, 2025 - It lets you convert a part of a string into an integer. The CharSequence is the type of the string you are working with, and you can specify where in the string to start (beginIndex) and where to end (endIndex).