String Conversion is done by converting
Byte, Short, Integer, Float, Character, Double, Long
data types into
String
.
String Conversion and toString
import java.io.*;
class StringConversiontoStringTest
{
public static void main(String arg[])
{
int a = 10;
float b = 20.5f;
char c = 'd';
double d = 19.5;
System.out.println(a + b + c + d);
String s1 = Integer.toString(a);
String s2 = Float.toString(b);
String s3 = Character.toString(c);
String s4 = Double.toString(d);
System.out.println(s1 + " " + s2+ " " + s3 + " " + s4);
double cake = 245.75;
String rate = Double.toString(cake);
String[] r = rate.split("\\.");
String r1 = r[0];
String r2 = r[1];
System.out.println("The Price of cake is " + r1 + " Rupees " + r2 + " Paise.");
}
}
OUTPUT150.0
10 20.5 d 19.5
The Price of cake is 245 Rupees 75 Paise.
DESCRIPTIONIn the program, ASCII value of d
character is 100 so sum of 10, 20.5, 100, 19.5 is 150 so 150 is printed. The int, float, char, double
values are converted to String
at LINE A, LINE B, LINE C, LINE D
and stored in s1, s2, s3, s4
variables respectively. The strings are concatenated and displayed in output. The cake rate of double
value is converted into string
and splits it into two parts using split
method where dot(.) is present and first part is taken as rupee and second part as paise.
THINGS TO TRY
- Apply
toString
method for different data types.
- Try to apply operations on strings which are obtained by other data types as cake rate.
- Try to get other string formats using
toString
method.