Convert String to int in Java
Learn to convert a Java String to int value. Note that string can contain a normal decimal value or a different value in other bases or radix.
The Integer.parseInt() parses a String to a signed int value. This method is an overloaded method with the following arguments:
- string: the string to be parsed.
- radix: radix to be used while parsing.
- beginIndex: beginning index, inclusive.
- endIndex: ending index, exclusive.
public static int parseInt(string) throws NumberFormatException < . >public static int parseInt(string, int radix) throws NumberFormatException < . >parseInt(string, int beginIndex, int endIndex, int radix) throws NumberFormatException
In the following Java program, we are parsing the string “1001” using all three above-mentioned methods and verifying that output.
Assertions.assertEquals(1001, Integer.parseInt("1001")); Assertions.assertEquals(513, Integer.parseInt("1001", 8)); Assertions.assertEquals(1001, Integer.parseInt("amount=1001", 7, 11, 10));
1.3. Throws NumberFormatException
- the argument string is null.
- the argument string length is zero i.e. empty string.
- the argument string is not a parsable integer in the specified radix. The default radix is 10.
Assertions.assertThrows(NumberFormatException.class, ()->< Integer.parseInt(null); >); Assertions.assertThrows(NumberFormatException.class, ()->< Integer.parseInt("abc"); >);
The Integer.valueOf() is very similar to parseInt() method – with only one difference that return type is Integer type instead of primitive int. In fact, if we look at the source code of valueOf() method, it internally calls parseInt() method.
It is also overloaded in two forms. Notice the method return type is Integer.
public static Integer valueOf(String s) throws NumberFormatException public static Integer valueOf(String s, int radix) throws NumberFormatException
Both methods throw the NumberFormatException in all cases, similar to parseInt().
Assertions.assertEquals(1001, Integer.valueOf("1001")); Assertions.assertEquals(513, Integer.valueOf("1001", 8)); Assertions.assertThrows(NumberFormatException.class, ()->< Integer.valueOf("abc"); >);
The Integer.decode() is another useful method for String to int conversion but only for decimal, hexadecimal and octal numbers. Note that:
- Decimal numbers should start with optional plus/minus sign i.e. +100, -2022, 334, 404.
- Octal numbers should start with an optional plus/minus sign and then the suffix ‘0’ (Zero). For example, +o100, -o2022, o334, 0404.
- Hex numbers should start with an optional plus/minus sign and then the suffix ‘0x’ or ‘0X’ (Zero and X). For example, +0x100, -0x2022, 0x334, 0x404.
public static Integer decode(String s) throws NumberFormatException
Let us see an example to understand it better.
Assertions.assertEquals(100, Integer.decode("+100")); Assertions.assertEquals(64, Integer.decode("+0100")); Assertions.assertEquals(256, Integer.decode("+0x100"));
In this quick Java tutorial, we learned to parse a string to int or Integer type. We also learned to parse the numbers in decimal, octal and hexadecimal formats.
Difference between valueOf and parseInt method in Java? Example
Both valueOf and parseInt methods are used to convert String to Integer in Java, but there is subtle differences between them. If you look at the code of valueOf() method, you will find that internally it calls parseInt() method to convert String to Integer, but it also maintains a pool of Integers from -128 to 127 and if the requested integer is in the pool, it returns an object from the pool. This means two integer objects returned using the valueOf() method can be the same b y the equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collectors.
Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns an Integer object, while parseInt() method returns an int primitive. Though, after introduci ng Autoboxing in Java 1.5, th is doesn’t count as a difference, but it’s worth knowing.
ParseInt vs valueOf in Java — Example
If you look code of parseInt() and valueOf() method from java.lang.Integer class, you will find that actual job of converting String to integer is done by parseInt() method, valueOf() just provide caching of frequently used Integer objects, Here is code snippet from the valueOf() method which makes things clear:
public static Integer valueOf(String s) throws NumberFormatException < return Integer.valueOf(parseInt(s, 10)); >
This method first calls parseInt() method, in order to convert String to primitive int, a nd then creates an Integer object from that value. You can see it internally maintains an Integer cache. If primitive int is within range of cache, it returns Integer object from the pool, otherwise, it creates a new object.
public static Integer valueOf(int i) < if(i >= -128 && i .high) return IntegerCache.cache[i + 128]; else return new Integer(i); >
And, if you like to see difference in tabular format here is a nice table to see the difference between valueOf and parseInt method in Java:
There is always confusion, whether to use parseInt() or valueOf() for converting String to primitive int and java.lang.Integer , I would suggest use parseInt() if you need primitive int and use valueOf() if you need java.lang.Integer objects. Since immutable objects are safe to be pooled and reusing them only reduces the load on the garbage collector , it’s better to use valueOf() if you need an Integer object.
5 comments :
I don’t understand why pool of Integers from -128 to 127 instead of others number ?
All these are basic api’s and people usually ignore the internals. But, its too good to know the implementations.
Thank you.
PS: i think there is a typo «parseInt() method to convert Integer to String»- it should be «to convert String to int»
@Anonymous, You are right, good understanding of basic API e.g. java.lang, java.util are extremely important for effective programming in Java. By the way good catch, parseInt() is used for converting String to primitive int 🙂
@Daniel, I don’t know the exact reason, but two observation make sense :
1) Those are most frequently used numbers, so it make sense to cache them.
2) They are also range of bytes -128 to 127
@Javin gr8 article , it has clearly explain the concepts . Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:
public static int parseInt(String s) throws NumberFormatException return parseInt(s,10);
>
public static Integer valueOf(String s, int radix) throws NumberFormatException return Integer.valueOf(parseInt(s,radix));
>
public static Integer valueOf(String s) throws NumberFormatException return Integer.valueOf(parseInt(s, 10));
>
As for parsing with a comma, I’m not familiar with one. I would sanitize them.
int million = Integer.parseInt(«1,000,000».replace(«,»,»»));
If efficiency is your concern, use int: it is much faster than Integer.
Otherwise, class Integer offers you at least a couple clear, clean ways:
Integer myInteger = new Integer(someString);
Integer anotherInteger = Integer.valueOf(someOtherString);
Разница между parseInt и valueOf в java?
Какая разница между этими двумя методами? Кажется, что они делают для меня то же самое (также для parseFloat() , parseDouble() , parseLong() и т.д., Как они отличаются от Long.valueOf(string) ?
Изменить: Кроме того, какой из них предпочтительнее и чаще используется по соглашению?
ОТВЕТЫ
Ответ 1
Ну, API для Integer.valueOf(String) действительно говорит, что String интерпретируется точно так, как если бы он был присвоен Integer.parseInt(String) . Однако valueOf(String) возвращает объект new Integer() , тогда как parseInt(String) возвращает примитив int .
Если вы хотите использовать потенциальные преимущества кэширования Integer.valueOf(int) , вы также можете использовать это бельмо на глазу:
Integer k = Integer.valueOf(Integer.parseInt("123"))
Теперь, если вам нужен объект, а не примитив, то использование valueOf(String) может быть более привлекательным, чем создание нового объекта из parseInt(String) , потому что первый последовательно присутствует в Integer , Long , Double и т.д.
Ответ 2
parseInt() возвращает примитивное целое число type (int), в результате чего valueOf возвращается java.lang.Integer, который является объектом представитель целого числа. Там являются обстоятельствами, в которых вы, возможно, захотите объект Integer, вместо примитивный тип.
Конечно, еще одно очевидное различие что intValue — это метод экземпляра в результате чего parseInt является статическим методом.
Ответ 3
new Integer(Integer.parseInt(s))
Разница valueOf() возвращает Integer , а parseInt() возвращает int (примитивный тип). Также обратите внимание, что valueOf() может возвращать кешированный экземпляр Integer , что может привести к запутывающим результатам, когда результат тестов == кажется прерывистым. До autoboxing может быть разница в удобстве, после java 1.5 это не имеет особого значения.
Кроме того, Integer.parseInt(s) может также принимать примитивный тип данных.
Ответ 4
Посмотрите на источники Java: valueOf использует parseInt :
/** * Parses the specified string as a signed decimal integer value. * * @param string * the string representation of an integer value. * @return an instance containing the integer value * represented by . * @throws NumberFormatException * if cannot be parsed as an integer value. * @see #parseInt(String) */ public static Integer valueOf(String string) throws NumberFormatException
/** * Parses the specified string as a signed decimal integer value. The ASCII * character \u002d ('-') is recognized as the minus sign. * * @param string * the string representation of an integer value. * @return the primitive integer value represented by . * @throws NumberFormatException * if cannot be parsed as an integer value. */ public static int parseInt(String string) throws NumberFormatException
Ответ 5
Integer.parseInt может просто возвращать int как собственный тип.
Integer.valueOf действительно может потребоваться выделить объект Integer, если это целое не является одним из предварительно выделенных. Это стоит больше.
Если вам нужен только собственный тип, используйте parseInt. Если вам нужен объект, используйте значениеOf.
Кроме того, из-за этого потенциального распределения автобоксинг на самом деле не является хорошим делом во всех отношениях. Это может замедлить работу.
Ответ 6
Потому что вы можете использовать jdk1.5 + и там он автоматически преобразуется в int. Таким образом, в вашем коде его первый возвращающий Integer, а затем автоматически преобразуется в int.
ваш код будет таким же, как
Ответ 7
Параметры parse * changes возвращают примитивные типы, а версии valueOf возвращают объекты. Я считаю, что версии valueOf также будут использовать внутренний пул ссылок, чтобы вернуть объект SAME для данного значения, а не только один экземпляр с тем же внутренним значением.
Ответ 8
Так как valueOf возвращает новый объект Integer, почему код ниже правильный?
String base5String = "230"; int result = Integer.valueOf(base5String);
Ответ 9
Если вы проверите класс Integer, вы найдете это значение метода parseInt вызова. Большая разница — это кеширование при вызове значения API. Он кэшируется, если значение находится между -128 и 127. Дополнительную информацию см. Ниже по ссылке
Ответ 10
public static Integer valueOf (String s)
- Аргумент интерпретируется как представляющее десятичное целое число, точно так же, как если бы аргумент был передан методу parseInt (java.lang.String).
- Результатом является объект Integer, который представляет целочисленное значение, указанное в строке.
- Другими словами, этот метод возвращает объект Integer, равный значению: new Integer (Integer.parseInt(s))
Ответ 11
- В случае ValueOf → он создает объект Integer. не примитивный тип, а не статический метод.
- В случае ParseInt.ParseFloat → он возвращает соответствующий примитивный тип. и является статическим методом.
Мы должны использовать любой, в зависимости от нашей потребности. В случае ValueOf, поскольку он создает экземпляр объекта. он будет потреблять больше ресурсов, если нам нужна только стоимость какого-либо текста, тогда мы должны использовать parseInt, parseFloat и т.д.