How to Convert String to Object in Java
We are going to start with the Conversion of String to Object in Java with its approach and programming, before that let us look into both String and Object and what do they mean?
In computer programming, a string is a sequence of characters that is used either as a constant or as a variable. The latter may allow for the mutation of its elements and the modification of their length, or it may be fixed (after creation). In computing, a string is a data type that is frequently implemented as an array of bytes (or words) that stores a succession of items, most commonly characters, using some character encoding.
A Java object is a member of a Java class (also known as an instance). There is an identity, a behaviour, and a state for each item. Fields (variables) hold an object’s state, whereas methods (functions) exhibit the object’s action. Templates, often known as classes, are used to build objects at runtime.
What’s the Approach?
- Import the
java.util
package to the class.
- Create a
Scanner class
object usingScanner sc=new Scanner (System.in);
- Accept the
user’s input
and store it in astring variable named str.
- Convert to object simply using
Object obj=str;
- Print the
Object
.
Also Read: How to Reverse a Number in Java using while loop
Java Program to Convert String to Object:
/* * TechDecode Tutorials * * How to Convert String to Object * */ import java.util.*; public class String_To_Object { public static void main(String args[]) { //Creating Scanner Object Scanner sc=new Scanner (System.in); //Accepting user input String str=sc.nextLine(); //Converting Object obj=str; System.out.println("String converted to Object is: "+obj); } }
Output: