Print int as string in java

How to convert an integer to a string in Java

There are many ways to convert an integer value (primitive int or an Integer object) into a string in Java. Unlike string to integer conversion, converting an integer to a string is a simple operation.

The toString() method is the most common method provided by every Java object that returns a string representation of the object. It can be used as a static method of the Integer class to convert a primitive int value into a string:

int number = 2344; String str = Integer.toString(number); System.out.println(str); // 2344 

If the integer variable is already an instance of Integer (wrapper class of primitive int ), there is no need to use the static method. It is better to call its toString() method:

Integer number = 2344; String str = number.toString(); System.out.println(str); // 2344 

The valueOf() method is a static method of the String class that accepts multiple data types like int , long , double , boolean , char , and Object , and returns its string representation:

int number = 2344; String str = String.valueOf(number); System.out.println(str); // 2344 

Internally, it calls the toString() method of the corresponding wrapper of the primitive value. For example, in the case of an integer, it calls the Integer.toString() method to perform the conversion. Therefore, it is better to use the Integer.toString() method.

Both StringBuildeer and StringBuffer are commonly used to concatenate different values into a single String object using the append() method. Here is an example that uses the StringBuilder class to convert an integer into a string:

int number = 2344; StringBuilder builder = new StringBuilder(); builder.append(number); String str = builder.toString(); System.out.println(str); // 2344 

The StringBuilder class is not thread-safe but is faster, whereas the StringBuffer is thread-safe but slower.

The String.format() method returns a formatted string using the specified format string and arguments. While this method is not meant to convert but rather format a string, it can be used to convert an integer to a string by using the %d format:

int number = 2344; String str = String.format("%d", number); System.out.println(str); // 2344 
// Text width String.format("|%10d|", 123); // | 123| // Justify left String.format("|%-10d|", 123); // |123 | // Pad with zeros String.format("|%010d|", 123); // |0000000123| // Positive number String.format("%+d", 123); // +123 // Thousands separator String.format("%,d", 1234567); // 1,234,567 // Enclose -ve number with parenthesis String.format("%o", 123); // (123) 

Finally, the last approach to convert an integer to a string is using string concatenation. Again, this is not the recommended way, as concatenation is not meant for conversion. When you concatenate an integer value with a string, the result is also a string:

int number = 2344; String str = "" + number; System.out.println(str); // 2344 

Converting an integer value into a string is one of the most common operations in Java. In this article, we have covered 5 different ways to achieve this. The rule of thumb is if the integer variable is a primitive int value, it is better to use the Integer.toString() or String.vaueOf() method. However, if the variable is already an instance of wrapper class Integer , there is no need to reinvent the wheel. Instead, call the toString() method of the Integer object to get a string representation of the value. Read this guide to learn about other data type conversions like string to date, a string to float, a string to double, and more in Java. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

Читайте также:  Senior php backend developer

You might also like.

Источник

Перевод 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, возвращаемая строка определяется соответствующим основанием.

Пример

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: целое число, которое должно быть преобразовано.

Читайте также:  Include google font html

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

Этот метод возвращает строковое представление аргумента 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(), чтобы получить строковое представление данных.

Читайте также:  Самая лучшая версия питона

Источник

Converting Between Numbers and Strings

Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
// The valueOf class method. String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

The output of this program is:

3 digits before decimal point. 2 digits after decimal point.

Источник

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