In this guide, we will learn how to convert String to Object in Java. Object is a parent class of all the classes in Java so you can simply assign a string to an object to convert it.
Program to Convert String to Object using simple assignment
You can use the assignment operator (=) to simply assign the string to object. Since Object is a parent class of String, it can store the string value.
class JavaExample { public static void main(String[] args) { String str = "BeginnersBook"; Object obj = str; //assigning string to object //the class of the value stored in the Object obj System.out.println("Class of the value stored in obj: " +obj.getClass().getName()); System.out.println("The value contained in obj is : "+obj); } }
Output:
Getting String instance of the Object class
We can use the forName()
method of Class to get an instance of Class, which represents a String. The syntax of forName()
method is:
public static Class<?> forName(String className) throws ClassNotFoundException
You can pass the desired class name to this method and it returns an instance of Class which represents object of the passed class. Since Class is a subclass of Object, when we use the getSuperclass() method of this class on the obtained instance, it returns Object class.
class JavaExample { public static void main(String[] args) throws Exception { // By passing the String class inside the forName() method // we can get an instance of Class that represents a String Class obj = Class.forName("java.lang.String"); // We can verify the class of the obtained instance System.out.println("Class name of obj: " + obj.getName()); // The superclass of obj should return Object class System.out.println("Super class of obj: "+obj.getSuperclass().getName()); } }
Output: