Convert Number to String

In this section, we will learn how to convert numbers
to String.
The following program provides you the functionality to convert numbers to
String.
Code Description:
In this program we have declared different type
of numbers like float, int, long etc as shown below. We have used
"valueOf()"
method here which is a method of String class. We use "String.valueOf()"
for numeric conversions and "toString()"
method to convert these numeric classes to
String as shown in the code below.
Here is the code of the program:
class NumToStr {
public static void main(String[] args) {
int i = 40;
float f = (float) 100.0;
long l = 3000000;
String s = new String();
s = String.valueOf(i);
System.out.println ("int i = " + s);
s = String.valueOf(f);
System.out.println ("float f = " + s);
s = String.valueOf(l);
System.out.println ("long l = " + s);
s = new Integer(i).toString();
System.out.println ("int i = " + s);
s = new Float(f).toString();
System.out.println ("float f = " + s);
s = new Long(l).toString();
System.out.println ("long l = " + s);
}
}
|
Output of the program:
C:\unique>javac NumToStr.java
C:\unique>java NumToStr
int i = 40
float f = 100.0
long l = 3000000
int i = 40
float f = 100.0
long l = 3000000
C:\unique> |
Download this example.

|