Convert Data type Java String

Convert Data type Java String

Summary: Many a times, it is required in Java coding to convert string to data types or data types to string. This tutorial "Convert Data type Java String" does this job.

In parsing operations, we convert strings into data types. Sometimes, code demands to convert data types and objects into strings; just the reverse of parsing. For example, the data to be displayed in a TextField must be in string format; say, the product two numbers to be displayed should be converted into string and then displayed. To come to the rescue, here comes a overloaded method valueOf().

Following are the details of the method.

  • String valueOf(int num): Converts num into a string and returns.

valueOf() is a static method of String class overloaded many times to accept any data type and object as parameter. That is, valueOf() can convert both data types and objects into strings. There comes a similar method toString() from Object class that converts only objects into string.

A program on "Convert Data type Java String" where all data types are converted to string using two styles with methods valueOf() and toString().

import java.util.Date;       
public class Conversions
  public static void main(String args[])
    int i = 100;
    double d = 100.6;
    byte b = 10;
    boolean cyclone = true;                     // Date object, currentDay

    String s1 = String.valueOf(i);              // int to string
    Date currentDay = new Date();       
    String s2 = String.valueOf(d);              // double to string
    String s3 = String.valueOf(b);              // byte to string
    String s4 = String.valueOf(cyclone);        // boolean to string
    String s5 = String.valueOf(currentDay);     // Date object to string
    String s6 = currentDay.toString();

    System.out.println("Using valueOf(): " + s5);
    System.out.println("Using toString(): " + s6);

Convert Data type Java String
Output screen of

import java.util.Date;

The above statement imports only Date class from java.util package and not all the classes. This way of importing the necessary class or classes saves a lot of memory on the client machine when the product is deployed.

With valueOf() method, the data types i, d, b and cyclone are converted into strings and printed.

String s5 = String.valueOf(currentDay);
String s6 = currentDay.toString();

The currentDay object is converted into strings s5 and s6 in two ways, in the above code. They print the same value, but the style of conversion is different; programmer can prefer his comfortable style.

2 thoughts on “Convert Data type Java String”

  1. Hi
    I have one doubt. When we use ArrayList in Java, we have to import java.util.ArrayList . But when we use String, it doesn’t require the import statement. why?

Leave a Comment

Your email address will not be published.