Sunday, September 6, 2009

Convert int to String using Wrapper in Java

Hello and welcome back to Java Code Online. I have seen a few comments from some of my readers, it was regarding an alternative way to convert an integer to String. This method uses the Wrapper Objects to convert an int to an Integer Object. Or you can say that, the process is:-

1. Convert a primitive to an Object using the Wrapper Classes.
2. Then convert the Wrapper Object in to a String.

Though it is a lengthier process, and is therefore rarely used for converting an ant to String. The best process is the one which I discussed in the previous article to convert an int to String. It is the most easiest and fastest way for making the conversion. Anyhow I will give you the alternative way also which I have discussed write now.

The Java Code starts by asking the user to enter an integer number. This number is then converted to an Integer Wrapper Object, which is later converted to a String, by using the toString() method on it.

The Java Code for a sample program on it is given below.

///////////////////////////////////////

/*
* This class converts an int number to an Integer Wrapper Object and then transforms that Object in to a String
*/

package developer;

import java.util.Scanner;

public class IntToStringUsingWrapper {


public static void main(String[] args) {

int number = 0;
System.out.println("Enter a number which would be taken as an Integer by the application");

Scanner scanInt = new Scanner(System.in);

//Execute if the number entered is an integer
if(scanInt.hasNextInt())
{
number = scanInt.nextInt();
}

//Wrap the number in the Integer Wrapper Object
Integer num = new Integer(number);

//The num is converted to a String
String strNum = num.toString();

//Use the toString() method to convert the object in to String
System.out.println("The number entered is: "+strNum);


}

}

///////////////////////////////////////

The output is something like shown below:-

///////////////////////////////////////

Enter a number which would be taken as an Integer by the application
33
The number entered is: 33

///////////////////////////////////////


hope that this article was helpful to resolve the issue of an alternative way to convert an int to a String. If you find the article useful, then do leave a comment. Keep checking Java Code Online for more Java topics.

Related articles:-
Convert int to String in Java
Java Code for Number of Words in a String

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.