Android java from string to int

Преобразование строки в int или Integer в Java

В этой статье мы покажем несколько способов преобразования строки в int или целое число.

Автор: baeldung
Дата записи

1. введение

Преобразование String в int или Integer – очень распространенная операция в Java. В этой статье мы покажем несколько способов решения этой проблемы.

Есть несколько простых способов справиться с этим базовым преобразованием.

2. Integer.parseInt()

Одним из основных решений является использование Integer выделенного статического метода: parseInt() , который возвращает примитивное int значение :

По умолчанию метод parseInt() предполагает, что заданная строка является целым числом base-10. Кроме того, этот метод принимает еще один аргумент для изменения этого значения по умолчанию radix. Например, мы можем разобрать двоичную строку s следующим образом:

Естественно, этот метод также можно использовать с любым другим радиксом, таким как 16 (шестнадцатеричный) или 8 (восьмеричный).

3. Integer.valueOf()

Другим вариантом было бы использовать статический Integer.valueOf() метод, который возвращает Integer экземпляр :

Аналогично, метод valueOf() также принимает пользовательский radix в качестве второго аргумента:

3.1. Целочисленный кэш

На первый взгляд может показаться, что значение методов() и parseInt() совершенно одинаковы. По большей части это верно — даже метод valueOf() делегирует метод parseInt внутренне.

Однако есть одно тонкое различие между этими двумя методами: метод valueOf() использует целочисленный кэш внутри . Этот кэш будет возвращать один и тот же Целочисленный экземпляр для чисел от -128 до 127 :

Поэтому настоятельно рекомендуется использовать valueOf() вместо parseInt() для извлечения коробочных целых чисел, так как это может привести к улучшению общего объема нашего приложения.

4. Конструктор целых чисел

Вы также можете использовать конструктор Integer :

Начиная с Java 9, этот конструктор был устарел в пользу других статических заводских методов, таких как value Of() или parseInt() . Даже до этого устаревания было редко уместно использовать этот конструктор. Мы должны использовать parseInt() для преобразования строки в примитив int или использовать valueOf() для преобразования ее в объект Integer .

5. Целое число.декодирование()

Кроме того, Integer.decode() работает аналогично Integer.value(), но также может принимать различные числовые представления :

Читайте также:  Лучшие планировщики бюджета для андроид

6. Исключение NumberFormatException

Все упомянутые выше методы выбрасывают исключение NumberFormatException, при обнаружении неожиданных String значений. Здесь вы можете увидеть пример такой ситуации:

7. С Гуавой

Конечно, нам не нужно придерживаться самого ядра Java. Вот как то же самое можно сделать с помощью Guava Ints.TryParse(), который возвращает null значение, если он не может разобрать входные данные:

Кроме того, метод TryParse() также принимает второй аргумент radix , аналогичный parseInt() и valueOf().

8. Заключение

В этой статье мы рассмотрели несколько способов преобразования экземпляров String в экземпляры int или Integer .

Все примеры кода, конечно, можно найти на GitHub .

Источник

How to easily Convert String to Integer in JAVA

Updated October 7, 2021

There are two ways to convert String to Integer in Java,

  1. String to Integer using Integer.parseInt()
  2. String to Integer using Integer.valueOf()

Let’s say you have a string – strTest – that contains a numeric value.

Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.

Output:

Hence, you need to convert a String to int before you peform numeric operations on it

Example 1: Convert String to Integer using Integer.parseInt()

Syntax of parseInt method as follows:

Pass the string variable as the argument.

This will convert the Java String to java Integer and store it into the specified integer variable.

Check the below code snippet-

Output:

Example 2: Convert String to Integer using Integer.valueOf()

Integer.valueOf() Method is also used to convert String to Integer in Java.

Following is the code example shows the process of using Integer.valueOf() method:

Output:

NumberFormatException

NumberFormatException is thrown If you try to parse an invalid number string. For example, String ‘Guru99’ cannot be converted into Integer.

Example:

Above example gives following exception in output:

Источник

Java Convert String to int examples

By Chaitanya Singh | Filed Under: Java Conversion

In this tutorial we will learn how to convert a String to int in Java. If a String is made up of digits like 1,2,3 etc, any arithmetic operation cannot be performed on it until it gets converted into an integer value. In this tutorial we will see two ways to convert String to int –

1. Java – Convert String to int using Integer.parseInt(String) method
2. Java – Convert String to int using Integer.valueOf(String) method

1. Java – Convert String to int using Integer.parseInt(String)

The parseInt() method of Integer wrapper class parses the string as signed integer number. This is how we do the conversion –

Here we have a String str with the value “1234”, the method parseInt() takes str as argument and returns the integer value after parsing.

Читайте также:  Последние модели телефонов андроид

Lets see the complete example –

Java Convert String to int example using Integer.parseInt(String)

Output:

Note: All characters in the String must be digits, however the first character can be a minus ‘-‘ sign. For example:

The value of inum would be -1234

Integer.parseInt() throws NumberFormatException, if the String is not valid for conversion. For example:

This would throw NumberFormatException . you would see a compilation error like this:

Lets see the complete code for String to int conversion.

2. Java – Convert String to int using Integer.valueOf(String)

Integer.valueOf(String) works same as Integer.parseInt(String) . It also converts a String to int value. However there is a difference between Integer.valueOf() and Integer.parseInt() , the valueOf(String) method returns an object of Integer class whereas the parseInt(String) method returns a primitive int value. The output of the conversion would be same whichever method you choose. This is how it can be used:

The value of inum would be 1122.

This method also allows first character of String to be a minus ‘-‘ sign.

Value of inum would be -1122.

Similar to the parseInt(String) method it also throws NumberFormatException when all the characters in the String are not digits. For example a String with value “11aa22” would throw an exception.

Lets see the complete code for conversion using this method.

Java Convert String to int example using Integer.valueOf(String)

Output:

Lets see another interesting example of String to int conversion.

Convert a String to int with leading zeroes

In this example, we have a string made up of digits with leading zeroes, we want to perform an arithmetic operation on that string retaining the leading zeroes. To do this we are converting the string to int and performing the arithmetic operation, later we are converting the output value to string using format() method.

Output:

Источник

Android java from string to int

Иногда возникают ситуации, когда имея величину какого-либо определенного типа, необходимо присвоить ее переменной другого типа. С переменными и их типами мы познакомились в прошлом уроке, в этом уроке мы рассмотрим наиболее популярные преобразования типов в Java:

Java преобразование строки в число (STRING to NUMBER)

В следующих примерах будет использована конструкция try-catch. Это необходимо для обработки ошибки, в случае, если строка содержит иные символы кроме чисел или число, выходящее за рамки диапазона допустимых значений определенного типа.

Например, строка «somenumber» не может быть переведена в тип int или в любой другой числовой тип. В это случае, при компеляции возникнет ошибка. Чтобы этого избежать, следует обезопаситься с помощью конструкции try-catch.

String to byte

C использованием конструктора

С использованием метода valueOf класса Byte

С использованием метода parseByte класса Byte

Перевод строки в массив байтов и обратно из массива байтов в строку

Читайте также:  Совместимость принтеров с андроид

String to short

C использованием конструктора

C использованием метода valueOf класса Short

C использованием метода parseShort класса Short

String to int

C использованием конструктора

C использованием метода valueOf класса Integer

C использованием метода parseInt класса Integer

String to long

C использованием конструктора

C использованием метода valueOf класса Long

C использованием метода parseLong класса Long

String to float

С использованием конструктора

C использованием метода valueOf класса Float

C использованием метода parseFloat класса Float

String to double

С использованием конструктора

C использованием метода valueOf класса Double

C использованием метода parseDouble класса Double

String to boolean

Преобразование строки в логический тип 2мя способами. Обратите внимание, что строка не соответствующая true, будет преобразована в логическое значение false.

Источник

Java – Convert String to int

By mkyong | Last updated: May 21, 2020

Viewed: 2,406,538 (+110 pv/w)

In Java, we can use Integer.parseInt() or Integer.valueOf() to convert String to int.

  • Integer.parseInt() – return primitive int .
  • Integer.valueOf() – return an Integer object.

For position or negative number in String , the convert is the same.

1. Integer.java

1.1 Review the JDK source code of the Integer class, both method signatures are the same, using parseInt(s,10) to do the conversion, but return a different result.

2. NumberFormatException

2.1 Both Integer.parseInt() and Integer.valueOf(String) methods will throw an NumberFormatException if the input is not a valid digit.

3. Integer.parseInt() – Convert String to int

3.1 This example converts a String 999 to a primitive type int .

3.2 For String 999AA , an invalid digit, it will throw NumberFormatException , and we catch it and display another more friendly error message.

4. Integer.valueOf – Convert String to Integer

4.1 This example converts a String 123 to an Integer object.

4.2 For input String number = «123A»

5. Best Practice – isDigit() + Integer.parseInt

The best practice is to check the inputs; the NumberFormatException thrown is expensive.

5.1 Review the following example, we use the regex String.matches(«3*») to check if the inputs are valid digit.

6. Java 8

6.1 Developers like Java 8, this example tries to use Java 8 Optional and Stream to convert a String into an Integer .

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

I am making a Movie Ticket System. User inputs seat number as “D13”. How to separate char row = ‘D’ and int column = 13?

You could use substring to separate your row from the column

Make a Object for this…

ha ha ha…
u r from guardian of the galaxy

Then I am ROOT
apt-get install GROOT
apt-get update

sudo dnf uninstall Groot
sudo dnf install Root version 1.0.2.Wrapper
sudo dnf uninstall Fedora 27
sudo dnf exit

Hello sir
this is well explained java String conversion.
really beautiful
thanks

I am getting still number format exception in httpservlet

Источник

Оцените статью