How to convert Integer to String in Java easily?

By informerfrk

Share on

When a developer programmer coding in Java, it can be found several time that she/he need to convert Integer to String. If you are new in Java then you may also still don’t know how to do it. In this post I am going to tell you how to convert integer into string easily in Java. Lets continue reading this post to know.

So how to convert Integer to String in Java? What is the code?

There are several ways to convert an integer into an string. I am going to tell you three simple ways.

Convert using String.valueOf(int) :

Using String.valueOf(int) you can easily convert an integer into a string. Here is the code below:

String numAsString = String.valueOf(-369);

But when you are going to use it in real work then you have to take the integer into a variable. So the code will be:

int number = -369;
String numAsString = String.valueOf(number);

Here the integer -369 is taken in the variable number and then the variable has used.

Convert using Integer.toString(int) :

Below is the code which will show you how to convert an integer into a string using Integer.toString(int):

int number = -369;
String numAsString = Integer.toString(number);

The above code is equivalent of the below code:

String numAsString = "-369";

 

Convert using new Integer(int).toString() :

There is another alternative method to do it. You can create an instance of the Integer class and then invoke it’s toString() method. This is a little less efficient method than the first two options I have already discussed above. This is because a new instance of Integer is created before conversion is performed.

Here is the Java code example below:

int number = -369;
Integer intInstance = new Integer(number);      
String numAsString = intInstance.toString();

The above code can be shorten. Look at the shortened code below:

int number = -369;
String numAsString = new Integer(number).toString();

 


There are some more ways available to convert an integer into an string in Java. Those are little bit less efficient than all the above example. I think now you know after reading this post how to convert an Integer into a string in Java. It is really so easy. Isn’t it? What you think?

Leave a Reply

Your email address will not be published. Required fields are marked *