Java Program to Convert String to Object

In the previous article we have discussed Java Program to Convert String to char

In this article we will see how to convert String to object.

Program To Convert String to object

Before going into the program, let’s see some examples of both  String and Object.

Example-1: String types

String a = "b";
String b = "3.333";

Let’s see different ways to convert String to Object.

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Method-1 : Java Program to Convert String to Object Using assignment operator

Object class is the parent class of all the classes so there will be a child class of the Object class,  internally using that concept we can directly assign a string to an object.

Approach :

  1. Take a String value and store it in a String variable input1.
  2. Assign that String variable to an object variable say ob.
  3. Print the object value .

Program:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        // creating scanner object
        Scanner sc = new Scanner(System.in);
        // input a  character through scanner class
        System.out.print("Enter a string : ");
        String input1=sc.next();
        // converting to an object
        Object ob = input1;
        System.out.println("Converted object is : " + ob);
    }
}
Output :

Enter a string : BtechGeeks
Converted object is : BtechGeeks

Method-2 : Java Program to Convert String to Object Using Class.forName() method

Class.forName() is a method to convert String to Object, which belongs to java.lang package. It usually creates an instance of java.lang.Class .

Approach :

  1. Take a String value and store it in a String variable input1.
  2. Assign that string variable to an class variable say c1.
  3. Print the class name value.

Program :

public class Main
{
    public static void main(String[] args) throws Exception
    {
        // Get the instance of the class
        // which is passed in forName() method as String
        Class c = Class.forName("java.lang.String");
        
        // Got the class
        System.out.println("Class name is : " + c.getName());
        
        // got the super class
        System.out.println("Super class name is : "
                           + c.getSuperclass().getName());
    }
}
Output:

Class name is : java.lang.String
Super class name is : java.lang.Object

Enhancing programming skills is very important no matter what language you have chosen. So,
practice frequently with these simple java programs examples and excel in coding the complex logic

Related Java Program: