Convert Data type Java String

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().


Convert Data type Java String

Output screen of Conversions.java

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

    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 Reply

Your email address will not be published. Required fields are marked *