Java Convert Integer to String

There are different ways of converting int to string by using different available methods. In this tutorial, we will learn some of them below.

1. Conversion Using Integer.toString(int)

Integer.toString(int) method takes integer value as an argument and returns the string representation of it.

Basic Syntax

Following is the basic syntax for toString() method which converts int to string and returns the processed string:

public static String toString(int i)

Example

Following is the example for Integer.toString(int i) method:

The output is:

String firstString = 100
String secondString = -111
Stringg thirdString = 500

2. Conversion Using String.valueOf(int)

You can also convert int to string using String class. In string class, the static method valueOf takes the integer as an argument and returns the String representation of it.

Basic Syntax

Following is the basic syntax for valueOf() method which converts int to string and returns the processed string:

public static String valueOf(int i)

Example

Following is the example for String.valueOf(int i) method:

The output should be:

String firstString = 230
String secondString = -330

3. Conversion Using String.format()

You can also use format() method from String class to convert the integer to String.

Basic Syntax

Following is the basic syntax for format() method which converts int to string and returns the processed string:

public static String format(String format, int i)

The above method takes two arguments first is the format and another is value to convert integer i.

Example

Following is the example for String.format(String format,int i) method:

In above program %d is used for integer value format like %f is used for Float value format.

The output should be:

String firstString = 135
String secondString = -170

4. Conversion Using StringBuffer/StringBuilder

By using StringBuffer we can concatenate Strings or perform an operation like appending string. by using StringBuffer conversion of int to string takes place in the following way.

Basic Syntax

Following is the basic syntax for format() method which converts int to string and returns the processed string:

public StringBuffer append(int i)

Example

Following is an example for append() method:

The output should be:

String firstString = 100
String secondString = -110

LEAVE A REPLY

Please enter your comment!
Please enter your name here