SlideShare a Scribd company logo
Effective Java   - Item 9 By Ferdous Mahmud Shaon  and Hasan Shihab Uddin Software Engineer, Escenic Bangladesh.
Item 9 :: Always override toString() While  java.lang.Object  provides an implementation of the toString() method, the string that it returns is generally not what the user of your class wants to see.  It consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code,  For example, “PhoneNumber@163b91”
Always override toString() - contd But the returned string should be: “a  concise  but  informative  representation that is easy for a person to read.”  “ PhoneNumber@163b91” is concise and easy to read, it is  not very informative  when compared to “(408) 867-5309”.  So, it is recommended that all subclasses of  java.lang.Object   should override this method.
Always override toString() - contd providing a  good toString implementation  makes your class much  more pleasant to use .   The toString method is automatically invoked when any object is passed to  println  method or the string  concatenation operator  (+). System.out.println("Failed to connect: " + phoneNumber); Without a good toString() implementation, the above output won’t be intelligible.
Always override toString() - contd The toString method should return  all of the interesting information  contained in the object, as in the phone number example just shown: area code, exchange, extension.  But it is  impractical  if the object is  large . In that case, the toString method should return  a summary  such as  “Manhattan white pages (1487536 listings)”
Always override toString() - contd One important decision you'll have to make when implementing a toString method is whether to specify the  format  of the return value in the  documentation . The advantage of specifying the format in the documentation is that it serves as a  standard ,  unambiguous ,  human-readable  representation of the object.
Always override toString() - contd
Always override toString() - contd If you specify the format, it's usually a good idea to provide a  matching   String constructor , so that programmers can easily translate back and forth between the object and its string representation. public final class PhoneNumber { private final int areaCode; private final int exchange; private final int extension; public PhoneNumber(int areaCode, int exchange, int extension) { this.areaCode = areaCode; this.exchange = exchange; this.extention = extention; }
Always override toString() - contd The  disadvantage  of  specifying the format  of the toString return value is that once you've specified it, you're  stuck with it for life . If you want to change the format in the future release, you'll have to break the code.  So if  format is not specified , you preserve the  flexibility to add information  or improve the format in a subsequent release. Whether or not you decide to specify the format, you should clearly document your intentions. If you specify the format, you should do so precisely.
Thank You
Ad

Recommended

Package in Java
Package in Java
lalithambiga kamaraj
 
Lesson 03 python statement, indentation and comments
Lesson 03 python statement, indentation and comments
Nilimesh Halder
 
Friend function & friend class
Friend function & friend class
Abhishek Wadhwa
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
String and string buffer
String and string buffer
kamal kotecha
 
Static keyword ppt
Static keyword ppt
Vinod Kumar
 
Python programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Control structures functions and modules in python programming
Control structures functions and modules in python programming
Srinivas Narasegouda
 
While , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
What is Python JSON | Edureka
What is Python JSON | Edureka
Edureka!
 
File handling in Python
File handling in Python
Megha V
 
Polymorphism in java
Polymorphism in java
Elizabeth alexander
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Classes and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Functions in python
Functions in python
colorsof
 
How Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) Works
Amit Tyagi
 
Class and Objects in Java
Class and Objects in Java
Spotle.ai
 
Javascript
Javascript
mussawir20
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
String Handling
String Handling
Bharat17485
 
single linked list
single linked list
Sathasivam Rangasamy
 
Operator Overloading in C++
Operator Overloading in C++
Mohammed Sikander
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
Edureka!
 
Linked List
Linked List
Ashim Lamichhane
 
C# operators
C# operators
baabtra.com - No. 1 supplier of quality freshers
 
Access specifier
Access specifier
zindadili
 
OOP V3.1
OOP V3.1
Sunil OS
 
Java applet - java
Java applet - java
Rubaya Mim
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
Sharbani Bhattacharya
 

More Related Content

What's hot (20)

While , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
What is Python JSON | Edureka
What is Python JSON | Edureka
Edureka!
 
File handling in Python
File handling in Python
Megha V
 
Polymorphism in java
Polymorphism in java
Elizabeth alexander
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Classes and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Functions in python
Functions in python
colorsof
 
How Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) Works
Amit Tyagi
 
Class and Objects in Java
Class and Objects in Java
Spotle.ai
 
Javascript
Javascript
mussawir20
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
String Handling
String Handling
Bharat17485
 
single linked list
single linked list
Sathasivam Rangasamy
 
Operator Overloading in C++
Operator Overloading in C++
Mohammed Sikander
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
Edureka!
 
Linked List
Linked List
Ashim Lamichhane
 
C# operators
C# operators
baabtra.com - No. 1 supplier of quality freshers
 
Access specifier
Access specifier
zindadili
 
OOP V3.1
OOP V3.1
Sunil OS
 
Java applet - java
Java applet - java
Rubaya Mim
 
While , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
What is Python JSON | Edureka
What is Python JSON | Edureka
Edureka!
 
File handling in Python
File handling in Python
Megha V
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginners
Kálmán "KAMI" Szalai
 
Classes and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Functions in python
Functions in python
colorsof
 
How Cascading Style Sheets (CSS) Works
How Cascading Style Sheets (CSS) Works
Amit Tyagi
 
Class and Objects in Java
Class and Objects in Java
Spotle.ai
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
Edureka!
 
Access specifier
Access specifier
zindadili
 
Java applet - java
Java applet - java
Rubaya Mim
 

Similar to Effective Java - Always override toString() method (20)

C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
Sharbani bhattacharya VB Structures
Sharbani bhattacharya VB Structures
Sharbani Bhattacharya
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
CHOOSE
 
Chapter2pp
Chapter2pp
J. C.
 
C programming language tutorial
C programming language tutorial
javaTpoint s
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
jaggernaoma
 
C –FAQ:
C –FAQ:
KITE www.kitecolleges.com
 
c.ppt
c.ppt
jazzcashlimit
 
C_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptx
maaithilisaravanan
 
Lk module3
Lk module3
Krishna Nanda
 
C and C++ programming basics for Beginners.pptx
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
C programming(part 3)
C programming(part 3)
Dr. SURBHI SAROHA
 
string , pointer
string , pointer
Arafat Bin Reza
 
Advanced+pointers
Advanced+pointers
Rubal Bansal
 
Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
imtiazalijoono
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
C interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
Hemantha Kulathilake
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
faithxdunce63732
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
CHOOSE
 
Chapter2pp
Chapter2pp
J. C.
 
C programming language tutorial
C programming language tutorial
javaTpoint s
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
jaggernaoma
 
C_Progragramming_language_Tutorial_ppt_f.pptx
C_Progragramming_language_Tutorial_ppt_f.pptx
maaithilisaravanan
 
C and C++ programming basics for Beginners.pptx
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
imtiazalijoono
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
C interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
Hemantha Kulathilake
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
faithxdunce63732
 
Ad

More from Ferdous Mahmud Shaon (6)

Getting started with Test Driven Development
Getting started with Test Driven Development
Ferdous Mahmud Shaon
 
Tips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering Career
Ferdous Mahmud Shaon
 
Introduction to HTML and CSS
Introduction to HTML and CSS
Ferdous Mahmud Shaon
 
Business Communcation
Business Communcation
Ferdous Mahmud Shaon
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
Composite Design Pattern
Composite Design Pattern
Ferdous Mahmud Shaon
 
Getting started with Test Driven Development
Getting started with Test Driven Development
Ferdous Mahmud Shaon
 
Tips to Kick-start your Software Engineering Career
Tips to Kick-start your Software Engineering Career
Ferdous Mahmud Shaon
 
Effective Java - Override clone() method judiciously
Effective Java - Override clone() method judiciously
Ferdous Mahmud Shaon
 
Ad

Recently uploaded (20)

K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 
K12 Tableau User Group virtual event June 18, 2025
K12 Tableau User Group virtual event June 18, 2025
dogden2
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Plate Tectonic Boundaries and Continental Drift Theory
Plate Tectonic Boundaries and Continental Drift Theory
Marie
 
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
THE PSYCHOANALYTIC OF THE BLACK CAT BY EDGAR ALLAN POE (1).pdf
nabilahk908
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
A Visual Introduction to the Prophet Jeremiah
A Visual Introduction to the Prophet Jeremiah
Steve Thomason
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Birnagar High School Platinum Jubilee Quiz.pptx
Birnagar High School Platinum Jubilee Quiz.pptx
Sourav Kr Podder
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wilde’s The Nightingal...
KaryanaTantri21
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
OBSESSIVE COMPULSIVE DISORDER.pptx IN 5TH SEMESTER B.SC NURSING, 2ND YEAR GNM...
parmarjuli1412
 

Effective Java - Always override toString() method

  • 1. Effective Java - Item 9 By Ferdous Mahmud Shaon and Hasan Shihab Uddin Software Engineer, Escenic Bangladesh.
  • 2. Item 9 :: Always override toString() While java.lang.Object provides an implementation of the toString() method, the string that it returns is generally not what the user of your class wants to see. It consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, For example, “PhoneNumber@163b91”
  • 3. Always override toString() - contd But the returned string should be: “a concise but informative representation that is easy for a person to read.” “ PhoneNumber@163b91” is concise and easy to read, it is not very informative when compared to “(408) 867-5309”. So, it is recommended that all subclasses of java.lang.Object should override this method.
  • 4. Always override toString() - contd providing a good toString implementation makes your class much more pleasant to use . The toString method is automatically invoked when any object is passed to println method or the string concatenation operator (+). System.out.println("Failed to connect: " + phoneNumber); Without a good toString() implementation, the above output won’t be intelligible.
  • 5. Always override toString() - contd The toString method should return all of the interesting information contained in the object, as in the phone number example just shown: area code, exchange, extension. But it is impractical if the object is large . In that case, the toString method should return a summary such as “Manhattan white pages (1487536 listings)”
  • 6. Always override toString() - contd One important decision you'll have to make when implementing a toString method is whether to specify the format of the return value in the documentation . The advantage of specifying the format in the documentation is that it serves as a standard , unambiguous , human-readable representation of the object.
  • 8. Always override toString() - contd If you specify the format, it's usually a good idea to provide a matching String constructor , so that programmers can easily translate back and forth between the object and its string representation. public final class PhoneNumber { private final int areaCode; private final int exchange; private final int extension; public PhoneNumber(int areaCode, int exchange, int extension) { this.areaCode = areaCode; this.exchange = exchange; this.extention = extention; }
  • 9. Always override toString() - contd The disadvantage of specifying the format of the toString return value is that once you've specified it, you're stuck with it for life . If you want to change the format in the future release, you'll have to break the code. So if format is not specified , you preserve the flexibility to add information or improve the format in a subsequent release. Whether or not you decide to specify the format, you should clearly document your intentions. If you specify the format, you should do so precisely.