Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
95 views
in JAVA by (117k points)
Explain Java Convert Object to String

Please log in or register to answer this question.

1 Answer

0 votes
by (117k points)

In Java, you can convert an object to a string using the toString() method. This method is defined in the Object class, which is the parent class of all classes in Java. The toString() method returns a string representation of the object.

To demonstrate this, let's consider an example where we have a custom class called Person with attributes such as name and age. We'll override the toString() method in this class to provide a custom string representation of the object.

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}
 

In the above code, we override the toString() method and provide a string representation of the Person object. The string includes the person's name and age.

Now, let's convert an instance of the Person class to a string:

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);
        String personString = person.toString();
        System.out.println(personString);
    }
}
 

In the main() method, we create a Person object with the name "John Doe" and age 30. Then, we call the toString() method on the person object, which returns a string representation of the object. Finally, we print the personString variable, which contains the converted object as a string.

The output will be:

Person [name=John Doe, age=30]
 

By default, the toString() method returns the class name along with the object's hash code. However, by overriding this method in your custom classes, you can provide a meaningful string representation of the object based on its attributes.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 17, 2023 in JAVA by kvdevika (117k points)
0 votes
1 answer
asked May 17, 2023 in JAVA by kvdevika (117k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...