We can convert Object to String in java using toString() method of Object class or String.valueOf(object) method.
Approach: Object to String using toString()
Java
public class ObjectToString {public static void main(String[] args) {Object obj = "Hello";String str = obj.toString();System.out.println(str);}}
Approach: StringBuffer object to String using toString()
Java
public class ObjectToString {public static void main(String[] args) {StringBuffer sb = new StringBuffer("Hello");String str = sb.toString();System.out.println(str);}}
Approach: StringBuffer object to String using valueOf()
Java
public class ObjectToString {public static void main(String[] args) {StringBuffer sb = new StringBuffer("Hello");String str = String.valueOf(sb);System.out.println(str);}}
Approach: Own java class object to String using toString()
Java
public class ObjectToString {public static void main(String[] args) {Person p = new Person("Ram Singh", 23);System.out.println("Person object in string " + p.toString());}}class Person {private String name;private int age;public Person(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + "]";}}
No comments:
Post a Comment