Parsing an integer to string in java

Перевод int в String на Java

Java позволяет вам преобразовывать значения из одного типа данных в другой при определенных условиях. Вы можете преобразовать строковую переменную в числовое значение, а числовое значение – в строковую переменную. В этой статье давайте рассмотрим, как перевести int в String на Java.

Преобразование с использованием Integer.toString(int)

Класс Integer имеет статический метод, который возвращает объект String, представляющий параметр int, указанный в функции Integer.toString(int). Этот подход, в отличие от других, может возвращать исключение NullPointerException.

Синтаксис

Есть два разных выражения для метода Integer.toString():

public static String toString(int i) public static String toString(int i, int radix)

Параметры

  • i: целое число, которое будет преобразовано.
  • radix: используемая система счисления базы для представления строки.

Значение radix является необязательным параметром, и если оно не установлено, для десятичной базовой системы значением по умолчанию является 10.

Возвращаемое значение

Возвращаемое значение для обоих выражений – строка Java, представляющая целочисленный аргумент «i». Если используется параметр radix, возвращаемая строка определяется соответствующим основанием.

Читайте также:  Java long to xml

Пример

package MyPackage; public class Method1 < public static void main(String args[]) < int n = Integer.MAX_VALUE; String str1 = Integer.toString(n); System.out.println("The output string is: " + str1); int m = Integer.MIN_VALUE; String str2 = Integer.toString(m); System.out.println("The output string is: " + str2); >>

Вывод

The output string is: 2147483647 The output string is: -2147483648

Перевод с использованием String.valueOf(int)

String.valueOf() – это статический служебный метод класса String, который может преобразовывать большинство примитивных типов данных в их представление String. Включает целые числа. Этот подход считается лучшей практикой благодаря своей простоте.

Синтаксис

public static String valueOf(int i)

Параметр

i: целое число, которое должно быть преобразовано.

Возвращаемое значение

Этот метод возвращает строковое представление аргумента int.

Пример

class Method2 < public static void main(String args[]) < int number = 1234; String str = String.valueOf(number); System.out.println("With valueOf method: string5 EnlighterJSRAW" data-enlighter-language="java">With valueOf method: string5 = 1234

Конвертация с помощью String.format()

String.format() – это новый альтернативный метод, который можно использовать для преобразования Integer в объект String. Хотя целью этого метода является форматирование строки, его также можно использовать для преобразования.

Синтаксис

Есть два разных выражения:

public static String format(Locale l, String format, Object… args) public static String format(String format, Object… args)

Параметры

Аргументы для этого метода:

  • l: локальный адрес для форматирования;
  • format: строка формата, которая включает спецификатор формата и иногда фиксированный текст;
  • args: аргументы, которые ссылаются на спецификаторы формата, установленные в параметре format.

Возвращаемое значение

Этот метод возвращает отформатированную строку в соответствии со спецификатором формата и указанными аргументами.

Пример

class Method3 < public static void main(String args[]) < int number = -1234; String str = String.format("%d", number); System.out.println("With format method: string EnlighterJSRAW" data-enlighter-language="java">With format method: string = -1234

Через DecimalFormat

DecimalFormat – это конкретный подкласс класса NumberFormat, который форматирует десятичные числа. Он имеет множество функций, предназначенных для анализа и форматирования чисел. Вы можете использовать его для форматирования числа в строковое представление по определенному шаблону.

Пример

import java.text.DecimalFormat; public class Method4 < public static void main(String[] args) < int number = 12345; DecimalFormat numberFormat = new DecimalFormat("##,###"); String str = numberFormat.format(12345); System.out.println("The number to be converted is: " + number); System.out.println("The string version of 12345 is: " + str); >>

Вывод

The number to be converted is: 12345 The string version of 12345 is: 12,345

Если вы знаете, как использовать метод DecimalFormat, это лучший вариант для преобразования Integer в String из-за уровня контроля, который можете иметь при форматировании. Можете указать количество знаков после запятой и разделитель запятых для лучшей читаемости, как показано в примере выше.

Конвертировать с использованием StringBuffer или StringBuilder

StringBuilder и StringBuffer – это классы, используемые для объединения нескольких значений в одну строку. StringBuffer является потокобезопасным, но медленным, тогда как StringBuilder не является поточно-ориентированным, но работает быстрее.

Пример 1

class Method5 < public static void main(String args[]) < int number1 = -1234; StringBuilder sb = new StringBuilder(); sb.append(number1); String str1 = sb.toString(); System.out.println("With StringBuilder method: string = " + str1); StringBuffer SB = new StringBuffer(); SB.append(number1); String str2 = SB.toString(); System.out.println("With StringBuffer method: string EnlighterJSRAW" data-enlighter-language="java">With StringBuilder method: string = -1234 With StringBuffer method: string = -1234

Объект StringBuilder представляет объект String, который можно изменять и обрабатывать как массив с последовательностью символов. Чтобы добавить новый аргумент в конец строки, экземпляр StringBuilder реализует метод append().

В конце важно вызвать метод toString(), чтобы получить строковое представление данных. Также вы можете использовать сокращенную версию этих классов.

Пример 2

class Method6 < public static void main(String args[]) < String str1 = new StringBuilder().append(1234).toString(); System.out.println("With StringBuilder method: string = " + str1); String str2 = new StringBuffer().append(1234).toString(); System.out.println("With StringBuffer method: string EnlighterJSRAW" data-enlighter-language="java">With StringBuilder method: string = -1234 With StringBuffer method: string = -1234

Наиболее важным является вызов метода toString(), чтобы получить строковое представление данных.

Источник

Int to String in Java – How to Convert an Integer into a String

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Int to String in Java – How to Convert an Integer into a String

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() method.
  • Using the String.format() method.
  • Using the DecimalFormat class.

How to Convert an Integer to a String in Java Using Integer.toString()

The Integer.toString() method takes in the integer to be converted as a parameter. Here’s what the syntax looks like:

Integer.toString(INTEGER_VARIABLE)

In the example above, we created an integer – age – and assigned a value of 2 to it.

To convert the age variable to a string, we passed it as a parameter to the Integer.toString() method: Integer.toString(age) .

We stored this new string value in a string variable called AGE_AS_STRING .

We then concatenated the new string variable with other strings: «The child is » + AGE_AS_STRING + » years old» .

But, would an error be raised if we just concatenated the age variable to these other strings without any sort of conversion?

The output above is the same as the example where we had to convert the integer to a string.

So how do we know if the type conversion actually worked?

We can check variable types using the Java getClass() object. That is:

Now we can verify that when the age variable was created, it was an Integer , and after type conversion, it became a String .

How to Convert an Integer to a String in Java Using String.valueOf()

The String.valueOf() method also takes the variable to be converted to a string as its parameter.

The code above is similar to that in the last section:

  • We created an integer called age .
  • We passed the age integer as a parameter to the String.valueOf() method: String.valueOf(age) .

You can also check to see if the type conversion worked using the getClass() object:

System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String

How to Convert an Integer to a String in Java Using String.format()

The String.format() method takes in two parameters: a format specifier and the variable to be formatted.

In the example above, we passed in two parameters to the String.format() method: «%d» and age .

«%d» is a format specifier which denotes that the variable to be formatted is an integer.

age , which is the second parameter, will be converted to a string and stored in the AGE_AS_STRING variable.

You can also check the variable types before and after conversion:

System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String

How to Convert an Integer to a String in Java Using DecimalFormat

The DecimalFormat class is used for formatting decimal numbers in Java. You can use it in different ways, but we’ll be using it to convert an integer to a string.

import java.text.DecimalFormat; class IntToStr < public static void main(String[] args) < int age = 2; DecimalFormat DFormat = new DecimalFormat("#"); String AGE_AS_STRING = DFormat.format(age); System.out.println("The child is " + AGE_AS_STRING + " years old"); // The child is 2 years old System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String >>
  • To be able to use the DecimalFormat class in the example above, we imported it: import java.text.DecimalFormat; .
  • We created the integer age variable.
  • We then created a new object of the DecimalFormat class called DFormat .
  • Using the object’s format() method, we converted age to a string: DFormat.format(age); .

Summary

In this article, we talked about converting integers to strings in Java.

We saw examples that showed how to use three different methods – Integer.toString() , String.valueOf() , String.format() — and the DecimalFormat class to convert variables from integers to strings.

Each example showed how to check the data type of a variable before and after conversion.

Источник

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