Menu
Topics Index
...
`


Strings > Special String Operations >
Siva Nookala - 04 Apr 2016
String Conversion and toString is a process, where different data types are converted into string object in order to operate on the value in string form.

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.");    
    }
}
OUTPUT

150.0
10 20.5 d 19.5
The Price of cake is 245 Rupees 75 Paise.

DESCRIPTION

In 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.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App