Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

How to convert Java String to Object

In Java, a String can be converted into an Object by simply using an assignment operator. This is because the Object class is internally the parent class of every class hence, String can be assigned to an Object directly.

Also, Class.forName() method can be used in order to convert the String into Object.

1. Using Assignment(=) opeartor

Example 1:

Here, the String is converted into Object using the assignment operator.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s = "welcome to studytonight";  
		Object ob = s;  
		System.out.println("Object value is " +ob);  
	}
}


Object value is welcome to studytonight

2. Using Class.forName() Method

The Class.forName() method is used to return the instance of Class class and is used to get the metadata of a class.

Example 2:

Here, the metadata and instance of the Class class are returned.

public class StudyTonight
{  
	public static void main(String args[])throws Exception
	{  
		String str = "studytonight";
		System.out.println(str);
		Object o = (Object)str;
		System.out.println(o);    
	}
}


studytonight
studytonight