By Unknown user


2011-04-07 18:27:54 8 Comments

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

30 comments

@Dubstep 2020-09-15 22:58:54

This can work,

Integer.parseInt(yourString);

@Rasoul Miri 2020-09-07 07:26:19

you can use their wayes:

String stringNumber = "0123456789";

1- Use parseInt

try {
   int number = Integer.parseInt(stringNumber);
}catch (NumberFormatException e){
   // Handel exception, mybe has space or alphabet 
}

2- Use valueOf

try {
   int number = Integer.valueOf(stringNumber);
}catch (NumberFormatException e){
   // Handel exception, mybe has space or alphabet 
}

@djm.im 2018-04-23 20:49:10

I am a little bit surprised that nobody mentioned the Integer constructor that takes String as a parameter.

So, here it is:

String myString = "1234";
int i1 = new Integer(myString);

Java 8 - Integer(String).

Of course, the constructor will return type Integer, and an unboxing operation converts the value to int.


Note 1: It's important to mention: This constructor calls the parseInt method.

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}

Note 2: It's deprecated: @Deprecated(since="9") - JavaDoc.

@Basilevs 2020-08-27 17:19:46

@Ajay Singh Meena 2020-07-13 07:51:31

You can have your own implementations for this, like:

public class NumericStringToInt {

    public static void main(String[] args) {
        String str = "123459";

        int num = stringToNumber(str);
        System.out.println("Number of " + str + " is: " + num);
    }

    private static int stringToNumber(String str) {

        int num = 0;
        int i = 0;
        while (i < str.length()) {
            char ch = str.charAt(i);
            if (ch < 48 || ch > 57)
                throw new NumberFormatException("" + ch);
            num = num * 10 + Character.getNumericValue(ch);
            i++;
        }
        return num;
    }
}

@Peter Mortensen 2020-08-21 16:11:01

What are the magic numbers 48 and 57? Can't (named) constants be used?

@garima garg 2020-04-29 09:14:51

There are different ways of converting a string int value into an Integer data type value. You need to handle NumberFormatException for the string value issue.

  1. Integer.parseInt

     foo = Integer.parseInt(myString);
    
  2. Integer.valueOf

     foo = Integer.valueOf(myString);
    
  3. Using Java 8 Optional API

     foo = Optional.of(myString).map(Integer::parseInt).get();
    

@Peter Mortensen 2020-08-21 16:06:19

Re "You need to handle NumberFormatException for the string value issue": How? By avoiding it happening altogether by one of these three methods? Can you make it more clear (without "Update: ", "Edit: " or similar)?

@Rohan Shah 2020-03-19 11:40:53

The two main ways to do this are using the method valueOf() and method parseInt() of the Integer class.

Suppose you are given a String like this

String numberInString = "999";

Then you can convert it into integer by using

int numberInInteger = Integer.parseInt(numberInString);

And alternatively, you can use

int numberInInteger = Integer.valueOf(numberInString);

But the thing here is, the method Integer.valueOf() has the following implementation in Integer class:

public static Integer valueOf(String var0, int var1) throws NumberFormatException {
    return parseInt(var0, var1);
}

As you can see, the Integer.valueOf() internally calls Integer.parseInt() itself. Also, parseInt() returns an int, and valueOf() returns an Integer

@skomisa 2020-04-12 03:34:24

How does this add anything? There are several older answers that have already provided these approaches. Please read existing answers before posting.

@Rajeev Ranjan 2019-02-11 13:15:50

You could use any of the following:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

@Peter Mortensen 2020-08-21 15:58:32

This appears to be plagiarised from Dmytro Shvechikov's answer (from 2017).

@Dmytro Shvechikov 2017-10-03 19:16:06

Methods to do that:

  1. Integer.parseInt(s)
  2. Integer.parseInt(s, radix)
  3. Integer.parseInt(s, beginIndex, endIndex, radix)
  4. Integer.parseUnsignedInt(s)
  5. Integer.parseUnsignedInt(s, radix)
  6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  7. Integer.valueOf(s)
  8. Integer.valueOf(s, radix)
  9. Integer.decode(s)
  10. NumberUtils.toInt(s)
  11. NumberUtils.toInt(s, defaultValue)

Integer.valueOf produces an Integer object and all other methods a primitive int.

The last two methods are from commons-lang3 and a big article about converting here.

@Shivanandam 2016-11-20 04:24:05

Here we go

String str = "1234";
int number = Integer.parseInt(str);
print number; // 1234

@Peter Mortensen 2019-09-02 23:01:56

This is already covered in the accepted answer (posted about 5 years prior).

@iKing 2016-04-20 09:54:39

int foo = Integer.parseInt("1234");

Make sure there is no non-numeric data in the string.

@Steve Smith 2017-06-14 11:15:23

This is exactly the same as the select answer.

@Dawood ibn Kareem 2017-10-29 18:28:34

There is no value to the site, in repeating an answer that someone else posted FIVE YEARS before you.

@Peter Mortensen 2019-09-02 23:08:41

This is already covered in the accepted answer (posted about 5 years prior).

@Oak 2014-03-20 23:51:19

Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length() - 2);
 int lastdigitASCII = number.charAt(number.length() - 1);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

 double semilastdigit = semilastdigitASCII - 48;  // A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit / 10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No "Magic" Expressions such as parseInt

@ChrisB 2015-08-14 14:23:54

Using type double for parsing an integer is not only a bad idea performance-wise. Values like 0.2 are periodic numbers in floating-point representation and cannot be represented precisely. Try System.out.println(0.1+0.2) to see the point -- the result will not be 0.3! Better stick with library code whereever you can, in this case Integer.parseInt().

@Holger 2016-03-04 10:47:41

It’s not clear what kind of problem this answer tries to solve, first, why anyone should ever have that restriction you describe, second, why you have to look at an ASCII table as you can simply use '0' for the character instead of 48 and never have to bother with its actual numeric value. Third, the entire detour with double values makes no sense at all as you are dividing by ten, just to multiply with ten afterwards. The result simply is semilastdigit * 10 + lastdigit as learnt in elementary school, when the decimal system was introduced…

@Oak 2016-05-02 08:49:52

@Holger I was personally given that restriction when first starting out programming, and also when I had to write (pen/paper) similar interactions in a test. It's uncommon, but it's a method that is easily understood and while not being the most efficient by miles it's a method that works decently enough for small projects. SO.SE is meant to help everyone, not just a few. I provided an alternative method, for those who are starting out by learning how to create a pseudo-algorithm and turning it into an algorithm rather than using premade java expressions. Although I did forget that '0' is cool

@Nathan Adams 2019-05-01 18:19:21

Why divide everything by 10 then multiply back by 10 again at the end?! Besides, "parseInt" isn't magic and it isn't an expression, it's an inbuilt library function that's been tested and proven over nearly 3 decades

@DavidS 2019-11-26 22:42:49

This isn't a good answer. The question is "How do I convert a String to an int in Java?" not, "How do I solve this homework problem with arbitrary restrictions?" It's StackOverflow, not HomeworkOverflow.

@skomisa 2020-04-12 02:28:01

You made the reason for using this novel approach very clear, so that in itself is not a concern. However, you stress that your approach uses "no repetitive cycles", yet your specific example bypasses that issue completely by hard-coding the solution (for a two digit number) to use only semilastdigit and lastdigit. How would you code your solution to avoid "repetitive cycles" if I provided you with a valid numeric string of arbitrary length (i.e. Any value between "-2147483648" and "2147483647"?)

@Dennis Ahaus 2013-10-20 13:18:52

Converting a string to an int is more complicated than just converting a number. You have think about the following issues:

  • Does the string only contain numbers 0-9?
  • What's up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
  • What's up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?

@SusanW 2016-10-05 22:52:39

Yes - and there's a nasty edge case around -2^31. If you try negating 2^31, you might run into difficulties......

@Billz 2013-09-11 02:08:24

Do it manually:

public static int strToInt(String str){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    // Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    // Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}

@yohm 2014-10-22 03:43:16

What if the input is greater than 2^32? What if the input contains non-numeric characters?

@Dawood ibn Kareem 2016-01-01 04:16:17

One of the things a programmer must learn on joining the workforce, if not before, is never to re-invent wheels. This may be a fun exercise, but don't expect your code to pass code review if you do this kind of thing in a commercial setting.

@Billz 2016-01-01 05:18:29

@yohm those are special case; you can handle with long and some regex; however, by then you can use parseInt.

@SusanW 2016-07-28 17:27:03

-1 Sorry, but this is a pretty poor algorithm, with lots of limitations, no error handling, and some weird anomalies (eg "" gives an exception, "-" will produce 0, and "+" produces -5). Why would anyone choose this over Integer.parseInt(s)? - I see the point about this being an interview question, but a) that doesn't imply you'd do it this way (which is what the questioner asked), and b) this answer's a pretty bad example anyway.

@Nathan Adams 2019-05-01 18:17:06

-1 because what if I want to parse a base 31 int? Integer.parseInt(str, 31) is a one liner to do that. Slightly facetious comment, but serious point underneath. Never re-invent wheels when someone else has already put the work in

@kaya3 2019-10-30 22:41:18

This code looks like it was adapted from a well-known library for fast IO in competitive programming contests. In that context, the input data is guaranteed to be valid, and solutions are graded on speed. It should be faster than Integer.parseInt because it does no validation.

@Rob Hruska 2011-04-07 18:29:41

String myString = "1234";
int foo = Integer.parseInt(myString);

If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(This treatment defaults a malformed number to 0, but you can do something else if you like.)

Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)

@Allison 2018-01-17 09:37:40

In addition to catching a NumberFormatException, the user should also be careful about the length of the strings they're passing in; if they're long enough to overflow an integer, they might want to consider using Long::parseLong instead.

@Letholdrus 2018-01-22 19:18:26

@Allison especially if using BIGINT field in a PostgreSQL auto incremented primary key field for instance. Much safer to use long

@JPRLCol 2018-01-25 20:17:14

You could check if the string is a Number first: stackoverflow.com/questions/1102891/…

@lokesh 2018-08-08 11:00:55

This method also throws exception when string is not a parsable integer in base 10. Use overloaded method to work in other bases. e.g. Integer.parseInt("1001", 8); for base 8. Source.

@Radioactive 2018-10-26 15:50:03

If you use Integer.parseInt prepare to put it inside a try catch block since this will throw are NumberFormat or InputMismatch Exception if it is not a valid number. Then in that case have proper exception handling at the catch block level. Otherwise as mentioned below you can also use the Integer class and then convert it to int.

@Kunda 2019-11-18 14:05:06

Since NumberFormatException is an instance of a RuntimeException, you can and probably should handle it - but you definitely don't have to!

@Kunda 2019-11-18 14:15:08

Also, while using Guava in combination with Java 8's Optional can be powerful, it's probably an overkill and not as concise as using NumberUtils.toInt(String str, int defaultValue) from the Apache commons-lang library: int foo = NumberUtils.toInt(myString, 0);

@Firzok Nadeem 2020-06-15 18:10:58

For this kinds of conversions, I usually use this site converttypes.com

@bdsl 2020-08-05 19:11:51

@Kunda I was about to make the same comment. And you should only handle it if you can do something sensible with it. Letting the program crash on malformed input, or letting a framework catch the exception is often likely to be better than picking an arbitrary default integer.

@Santosh Jadi 2018-09-12 09:07:04

It can be done in seven ways:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

String number = "999";
  1. Ints.tryParse:

    int result = Ints.tryParse(number);

  2. NumberUtils.createInteger:

    Integer result = NumberUtils.createInteger(number);

  3. NumberUtils.toInt:

    int result = NumberUtils.toInt(number);

  4. Integer.valueOf:

    Integer result = Integer.valueOf(number);

  5. Integer.parseInt:

    int result = Integer.parseInt(number);

  6. Integer.decode:

    int result = Integer.decode(number);

  7. Integer.parseUnsignedInt:

    int result = Integer.parseUnsignedInt(number);

@Sundararaj Govindasamy 2019-02-05 16:24:14

NumberUtils handles null and empty scenarios as well.

@Stefan Dollase 2016-04-04 03:13:08

Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

In my opinion, this special case should be handled by returning an empty Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

Example usage:

// prints "12"
System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
// prints "-1"
System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
// prints "invalid"
System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));

While this is still using exceptions for flow control internally, the usage code becomes very clean. Also, you can clearly distinguish the case where -1 is parsed as a valid value and the case where an invalid String could not be parsed.

@Sachini Witharana 2020-03-11 16:43:46

By using this method you can avoid errors.

String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};

@Peter Mortensen 2020-08-21 16:00:54

Why is an empty if necessary? Why not just Integer.parseInt(myString), out myInt?

@Sachini Witharana 2020-08-25 04:19:23

@PeterMortensen without the if condition we cannot out myInt

@shellhub 2019-10-22 12:32:08

As I write on GitHub:

public class StringToInteger {
    public static void main(String[] args) {
        assert parseInt("123") == Integer.parseInt("123");
        assert parseInt("-123") == Integer.parseInt("-123");
        assert parseInt("0123") == Integer.parseInt("0123");
        assert parseInt("+123") == Integer.parseInt("+123");
    }

    /**
     * Parse a string to integer
     *
     * @param s the string
     * @return the integer value represented by the argument in decimal.
     * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
     */
    public static int parseInt(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        boolean isNegative = s.charAt(0) == '-';
        boolean isPositive = s.charAt(0) == '+';
        int number = 0;
        for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
            if (!Character.isDigit(s.charAt(i))) {
                throw new NumberFormatException("s=" + s);
            }
            number = number * 10 + s.charAt(i) - '0';
        }
        return isNegative ? -number : number;
    }
}

@Thijser 2013-10-20 13:11:49

You can also begin by removing all non-numerical characters and then parsing the integer:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);

But be warned that this only works for non-negative numbers.

@user289086 2014-10-11 14:00:14

This will cause -42 to be parsed as 42.

@Holger 2016-03-04 11:01:46

Yeah, this only works for non negative numbers which are correct to begin with and hence, don’t need this replacement step. For every other case, this attempt to automatically fix it, will make things worse (as almost every attempt to automatically fix something). If I pass in "4+2", I’ll get 42 as a result without any hint about that what I tried to do was misguided. The user will get the impression that entering basic expressions like 4+2 was a valid input, but the application continues with a wrong value. Besides that, the type is String, not string

@apm 2016-08-19 10:57:06

Or change first line to--> string mystr = mystr.replaceAll( "[^\\d\\-]", "" );

@ishant kulshreshtha 2019-02-06 20:13:51

Some of the ways to convert String into Int are as follows:

  1. You can use Integer.parseInt():

    String test = "4568";
    int new = Integer.parseInt(test);
    
  2. Also you can use Integer.valueOf():

    String test = "4568";
    int new = Integer.valueOf(test);
    

@Wai Ha Lee 2019-06-15 09:15:24

Both examples are the same

@Alireza Fattahi 2016-07-26 05:26:27

As mentioned, Apache Commons' NumberUtils can do it. It returns 0 if it cannot convert a string to an int.

You can also define your own default value:

NumberUtils.toInt(String str, int defaultValue)

Example:

NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1)     = 1
NumberUtils.toInt(null, 5)   = 5
NumberUtils.toInt("Hi", 6)   = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty("  32 ", 1)) = 32;

@nxhoaf 2016-08-01 14:44:08

Apart from the previous answers, I would like to add several functions. These are results while you use them:

public static void main(String[] args) {
  System.out.println(parseIntOrDefault("123", 0)); // 123
  System.out.println(parseIntOrDefault("aaa", 0)); // 0
  System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
  System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
}

Implementation:

public static int parseIntOrDefault(String value, int defaultValue) {
  int result = defaultValue;
  try {
    result = Integer.parseInt(value);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
  int result = defaultValue;
  try {
    String stringValue = value.substring(beginIndex, endIndex);
    result = Integer.parseInt(stringValue);
  }
  catch (Exception e) {
  }
  return result;
}

@Vitalii Fedorenko 2016-08-06 17:56:29

Google Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

@Aditya 2016-08-18 07:07:24

For a normal string you can use:

int number = Integer.parseInt("1234");

For a String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());

@Raman Sahasi 2017-04-24 05:36:19

In programming competitions, where you're assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don't need any of that) and will be a bit more efficient.

  1. For valid positive integer:

    private static int parseInt(String str) {
        int i, n = 0;
    
        for (i = 0; i < str.length(); i++) {
            n *= 10;
            n += str.charAt(i) - 48;
        }
        return n;
    }
    
  2. For both positive and negative integers:

    private static int parseInt(String str) {
        int i=0, n=0, sign=1;
        if (str.charAt(0) == '-') {
            i = 1;
            sign = -1;
        }
        for(; i<str.length(); i++) {
            n* = 10;
            n += str.charAt(i) - 48;
        }
        return sign*n;
    }
    
  3. If you are expecting a whitespace before or after these numbers, then make sure to do a str = str.trim() before processing further.

@Pankaj Mandale 2017-08-12 14:25:51

One method is parseInt(String). It returns a primitive int:

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

The second method is valueOf(String), and it returns a new Integer() object:

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);

@Peter Mortensen 2019-09-02 22:56:26

Isn't this covered in previous answers?

@Anup Gupta 2017-09-01 06:53:39

This is a complete program with all conditions positive and negative without using a library

import java.util.Scanner;


public class StringToInt {

    public static void main(String args[]) {
        String inputString;
        Scanner s = new Scanner(System.in);
        inputString = s.nextLine();

        if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
            System.out.println("Not a Number");
        }
        else {
            Double result2 = getNumber(inputString);
            System.out.println("result = " + result2);
        }
    }


    public static Double getNumber(String number) {
        Double result = 0.0;
        Double beforeDecimal = 0.0;
        Double afterDecimal = 0.0;
        Double afterDecimalCount = 0.0;
        int signBit = 1;
        boolean flag = false;

        int count = number.length();
        if (number.charAt(0) == '-') {
            signBit = -1;
            flag = true;
        }
        else if (number.charAt(0) == '+') {
            flag = true;
        }
        for (int i = 0; i < count; i++) {
            if (flag && i == 0) {
                continue;
            }
            if (afterDecimalCount == 0.0) {
                if (number.charAt(i) - '.' == 0) {
                    afterDecimalCount++;
                }
                else {
                    beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
                }
            }
            else {
                afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
                afterDecimalCount = afterDecimalCount * 10;
            }
        }
        if (afterDecimalCount != 0.0) {
            afterDecimal = afterDecimal / afterDecimalCount;
            result = beforeDecimal + afterDecimal;
        }
        else {
            result = beforeDecimal;
        }
        return result * signBit;
    }
}

@Dorian Gray 2017-11-10 11:38:23

There is no need to reinvent the wheel, just use Integer.parseInt.

@Anup Gupta 2017-11-11 05:38:46

@TobiasWeimer yes, we can do but this is without using library

@Anup Gupta 2017-11-11 14:26:43

@TobiasWeimer, some people need this how to do without using Library.

@Dorian Gray 2017-11-11 15:00:06

No, no one needs it because it is a function inside the JDK, not some third party plugin.

@Lukas Bauer 2017-10-06 19:00:22

Use Integer.parseInt(yourString).

Remember the following things:

Integer.parseInt("1"); // ok

Integer.parseInt("-1"); // ok

Integer.parseInt("+1"); // ok

Integer.parseInt(" 1"); // Exception (blank space)

Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

Integer.parseInt(""); // Exception (not 0 or something)

There is only one type of exception: NumberFormatException

@The Coding Wombat 2018-10-24 16:02:50

Does the int maximum value here also give a NumberFormatException?

@Lukas Bauer 2018-11-24 15:02:13

No, the maximum value is stil okay

@Poorna Senani Gamage 2018-07-27 08:45:03

public static int parseInt(String s)throws NumberFormatException

You can use Integer.parseInt() to convert a String to an int.

Convert a String, "20", to a primitive int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

Output-20

If the string does not contain a parsable integer, it will throw NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf(String s)throws NumberFormatException

You can use Integer.valueOf(). In this it will return an Integer object.

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

Output-20

References https://docs.oracle.com/en/

@Nisarg 2018-11-09 15:24:12

Convert a string to an integer with the parseInt method of the Java Integer class. The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

Overlooking the exception it can throw, use this:

int i = Integer.parseInt(myString);

If the String signified by the variable myString is a valid integer like “1234”, “200”, “1”, and it will be converted to a Java int. If it fails for any reason, the change can throw a NumberFormatException, so the code should be a little longer to account for this.

For example, Java String to int conversion method, control for a possible NumberFormatException

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // Use this if you want to test the exception below
    String s = "1234";

    try
    {
      // The String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // Print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

If the change attempt fails – in this case, if you can try to convert the Java String test to an int — the Integer parseInt process will throw a NumberFormatException, which you must handle in a try/catch block.

@Peter Mortensen 2019-09-02 22:43:19

Why is s.trim() necessary?

Related Questions

Sponsored Content

31 Answered Questions

[SOLVED] How can I cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1448330 View
  • 3281 Score
  • 31 Answer
  • Tags:   c# enums casting int

28 Answered Questions

[SOLVED] How do I parse a string to a float or int?

70 Answered Questions

[SOLVED] How to replace all occurrences of a string?

40 Answered Questions

63 Answered Questions

[SOLVED] What is the difference between String and string in C#?

28 Answered Questions

[SOLVED] Easiest way to convert int to string in C++

3 Answered Questions

35 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3978896 View
  • 1677 Score
  • 35 Answer
  • Tags:   java string split

33 Answered Questions

[SOLVED] How do I check if a string is a number (float)?

59 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

Sponsored Content