In this section you will learn to convert Object to String in java. It is sometimes necessary to convert object to String because you need to pass it to the method that accept String only.
Converting object to String
In this section you will learn to convert Object to String in java. It is sometimes necessary to convert object to String because you need to pass it to the method that accept String only. Object is a class of java.lang package. Java provide two method to convert to string they are as follows:
The toString() Method - If u want to convert any object into string then toString() is used, toString() method return the string representation of object. Java Compiler invoke toString() method while printing, So overriding toString() method will give the result as expected.
The valueOf() - If u want to convert any variable to string then this method is used, a static method provided by java to convert to String.
Example : Code to convert the object to string.
public class ObjecttoString { public static void main(String args[]) { Object ob=10; String st=ob.toString(); System.out.println("After conversion = "+st); } }
Output : After compiling and executing the above program.