Signup/Sign In
LAST UPDATED: DECEMBER 1, 2020

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



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.