Question: How do I convert numeric values to Strings with Java?
Converting numeric values to Strings with Java is pretty easy. The String class contains a method named "valueOf()" that can be used, and the numeric classes also contain "toString()" methods that can be used for the conversion.
Let's take a look at a few examples. Assuming that the variable i is an int, f is a float, d is a double, and l (the letter pronounced "el") is a long, the following examples show how you can convert each numeric type to a String.
Using String.valueOf() for the conversions, you'd write the Java code this way:
String s = String.valueOf(i); String s = String.valueOf(f); String s = String.valueOf(d); String s = String.valueOf(l);
Using the toString() method of the numeric classes (Integer, Float, Double, and Long), you'd write the conversions this way:
String s = new Integer(i).toString(); String s = new Float(f).toString(); String s = new Double(d).toString(); String s = new Long(l).toString();
As an additional example, the simple (some people would call it trivial) Java program shown below demonstrates how this is done in a working Java program:
// Convert.java
// A sample Java program by Alvin Alexander, devdaily.com
class Convert {
public static void main(String[] args) {
int i = 100;
float f = (float) 200.0;
double d = 400.0;
long l = 100000;
String s = new String();
//--------------------------------------------//
// Examples using "valueOf()" method of the //
// String class. //
//--------------------------------------------//
s = String.valueOf(i);
System.out.println ("int i = " + s);
s = String.valueOf(f);
System.out.println ("float f = " + s);
s = String.valueOf(d);
System.out.println ("double d = " + s);
s = String.valueOf(l);
System.out.println ("long l = " + s);
//------------------------------------------------//
// Examples using the "toString()" method of the //
// numeric classes //
//------------------------------------------------//
s = new Integer(i).toString();
System.out.println ("int i = " + s);
s = new Float(f).toString();
System.out.println ("float f = " + s);
s = new Double(d).toString();
System.out.println ("double d = " + s);
s = new Long(l).toString();
System.out.println ("long l = " + s);
}
}
There is much more content related to Java and the String class on the blog, including these posts:
good
GOOD RESOURCE!!!!!!!!! VERY THANKS!
Post new comment