Convert from integer to string 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.

Читайте также:  Python аналитика для начинающих

You might also like.

Источник

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.

Источник

Читайте также:  Python sqlite3 update value

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.

Читайте также:  Styling title attribute html

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.

Источник

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