- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Override the toString() method in a Java Class
A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
A program that demonstrates this is given as follows:
Example
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public String toString() { return rno + " " + name; } } public class Demo { public static void main(String[] args) { Student s = new Student(101, "Susan Bones"); System.out.println("The student details are:"); System.out.println(s); } }
Output
The student details are: 101 Susan Bones
Now let us understand the above program.
The Student class is created with data members rno, name. The constructor Student() initializes rno and name. The overridden method toString() displays a string representation of object s. A code snippet which demonstrates this is as follows:
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public String toString() { return rno + " " + name; } }
In the main() method, an object s of class Student is created with values 101 and “Susan Bones”. Then the object s is printed. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { Student s = new Student(101, "Susan Bones"); System.out.println("The student details are:"); System.out.println(s); } }
- Related Articles
- The toString() method of Java AbstractCollection class
- Is it possible to override toString method in an array using Java?
- Java toString() method.
- Is it possible to override a Java method of one class in same?
- LocalDateTime toString() method in Java
- LocalTime toString() method in Java
- MonthDay toString() Method in Java
- Instant toString() method in Java
- LocalDate toString() method in Java
- ShortBuffer toString() method in Java
- Provider toString() method in Java
- Duration toString() method in Java
- Convert Long into String using toString() method of Long class in java
- Java Signature toString() method
- The toString() method of CopyOnWriteArrayList in Java

Advertisements