Java toString method
toString method inwards Java is used to render clear as well as concise information virtually Object inwards human readable format. Influenza A virus subtype H5N1 correctly overridden toString method tin assistance inwards logging as well as debugging of Java program past times providing valuable as well as meaningful information. Since toString() is defined inwards java.lang.Object cast as well as its default implementation don't render much information, it's e'er a best practise to override the toString method inwards sub class. In fact, if you lot are creating value cast or domain cast e.g. Order, Trade or Employee, always override equals,hashCode, compareTo as well as toString method inwards Java. By default toString implementation produces output inwards the cast package.class@hashCode e.g. for our toString() example, Country class’ toString() method volition impress test.Country@18e2b22 where 18e2b22 is hashCode of an object inwards hex format, if you lot telephone yell upwards hashCode method it volition render 26094370, which is decimal equivalent of 18e2b22. This information is non real useful piece troubleshooting whatever problem.
Let’s encounter a existent life illustration where you lot are troubleshooting network connectivity issues, inwards instance of this you lot desire to know which host as well as port your organisation is trying to connect as well as if Socket or ServerSocket cast solely impress default toString information than its impossible to figure out the actual problem, but amongst a decent toString implementation they tin impress useful information similar hostname as well as port.
In this Java tutorial nosotros volition encounter about tips to override toString method amongst code examples.
Let’s encounter a existent life illustration where you lot are troubleshooting network connectivity issues, inwards instance of this you lot desire to know which host as well as port your organisation is trying to connect as well as if Socket or ServerSocket cast solely impress default toString information than its impossible to figure out the actual problem, but amongst a decent toString implementation they tin impress useful information similar hostname as well as port.
In this Java tutorial nosotros volition encounter about tips to override toString method amongst code examples.
How to override toString method inwards Java:
overriding whatever method inwards Java, you lot ask to follow rules of method overriding. Any agency at that spot are many agency to implement or override toString() method e.g. You tin write this method manually, you lot tin utilization IDE similar Netbeans as well as Eclipse to generate toString method or you lot tin utilization Apache park ToStringBuilder to generate toString method inwards multiple styles similar unmarried line, multi-line etc. Here are few points to retrieve piece overriding toString() method inwards Java, which volition assistance you lot to acquire most from your toString() implementation.
Print formatted appointment e.g. dd-MM-yy instead of raw date
This is real helpful tip piece overriding Java’s toString() method. Since toString() of java.util.Date cast does non impress formatted appointment as well as includes lots of details which is non e'er necessary. If you lot are using a particular DateFormat e.g. dd-MM-yy inwards your application, they you lot definitely desire to encounter dates on that format instead of default. IDE usually does non generate formatted Date output as well as this is something you lot ask to do past times yourself but its worth of effort. See How to impress Date inwards ddMMyy format inwards Java for to a greater extent than details on formatting Date inwards Java. You tin either utilization SimpleDateFormat cast or Joda Date fourth dimension library for this purpose.
Document toString format
If your toString() method is non printing information inwards damage of field=value, Its practiced sentiment to document format of toString, particularly for value objects similar Employee or Student. For illustration if toString() method of Employee prints "John-101-Sales-9846387321" than its practiced sentiment to specify format every bit "name-id-department-contact", but at the same fourth dimension don't permit your client extract information from toString() method as well as you lot should e'er render corresponding getter methods similar getName(), getId(), getContact() etc, because extracting information from toString() representation of Object is frail as well as fault prone as well as client should e'er a cleaner agency to asking information.
Use StringBuilder to generate toString output
If you lot writing code for toString() method inwards Java, hence utilization StringBuilder to append private attribute. If you lot are using IDE similar Eclipse, Netbeans or IntelliJ hence likewise using StringBuilder as well as append() method instead of + operator to generate toString method is practiced way. By default both Eclipse as well as Netbeans generate toString method amongst concatenation operator .
Use @Override annotation
Using @Override notation piece overriding method inwards Java is ane of the best practise inwards Java. But this tip is non every bit of import every bit it was inwards instance of overriding equals() as well as compareTo() method, every bit overloading instead of overriding tin do to a greater extent than subtle bugs there. Anyway it’s best to using @Override annotation.
Print contents of Array instead of printing array object
Array is an object inwards Java but it doesn’t override toString method as well as when you lot impress array, it volition utilization default format which is non real helpful because nosotros want to encounter contents of Array. By the agency this is about other argue why char[] array are preferred over String for storing sensitive information e.g. password. Take a 2nd to encounter if printing content of array helps your user or non as well as if it brand feel than impress contents instead of array object itself. Apart from functioning argue prefer Collection similar ArrayList or HashSet over Array for storing other objects.
Bonus Tips
Here are few to a greater extent than bonus tips on overriding toString method inwards Java
1. Print output of toString inwards multiple trace of piece of job or unmarried trace of piece of job based upon it length.
2. Include sum qualified advert of cast inwards toString representation e.g. package.class to avoid whatever confusion/
3. You tin either skip cypher values or present them, its amend to acquire out them. Sometime they are useful every bit they betoken which fields are cypher at the fourth dimension of whatever incident e.g. NullPointerException.
4. Use substitution value format similar member.name=member.value every bit most of IDE likewise follows that.
5. Include inherited members if you lot matter they render must bring information inwards youngster class.
6. Sometime an object contains many optional as well as mandatory parameters similar nosotros shown inwards our Builder designing example, when its non practically possible to impress all fields inwards those cases printing a meaningful information, non necessary fields is better.
toString Example inwards Java
We volition utilization next cast to demonstrate our toString examples for Netbeans, Eclipse as well as Apache's ToStringBuilder utility.
/**
* Java program to demonstrate How to override toString() method inwards Java.
* This Java programme shows How tin you lot utilization IDE similar Netbeans or Eclipse
* as well as Open rootage library similar Apache park ToStringBuilder to
* Java program to demonstrate How to override toString() method inwards Java.
* This Java programme shows How tin you lot utilization IDE similar Netbeans or Eclipse
* as well as Open rootage library similar Apache park ToStringBuilder to
* override toString inwards Java.
*
* @author .blogspot.com
*/
public class Country{
private String name;
private String capital;
private long population;
private Date independenceDay;
public Country(String name){
this.name = name;
}
public String getName(){ return name; }
public void setName(String name) {this.name = name;}
public String getCapital() {return capital;}
public void setCapital(String capital) {this.capital = capital;}
public Date getIndependenceDay() {return independenceDay;}
public void setIndependenceDay(Date independenceDay) {this.independenceDay = independenceDay;}
public long getPopulation() { return population; }
public void setPopulation(long population) {this.population = population; }
@Override
public String toString() {
return "Country{" + "capital=" + upper-case alphabetic quality + ",
population=" + population + ",
independenceDay=" + independenceDay + '}';
}
public void setIndependenceDay(String date) {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
this.independenceDay = format.parse(date);
} catch (ParseException ex) {
Logger.getLogger(Country.class.getName()).log(Level.SEVERE, null, ex);
}
}
*
* @author .blogspot.com
*/
public class Country{
private String name;
private String capital;
private long population;
private Date independenceDay;
public Country(String name){
this.name = name;
}
public String getName(){ return name; }
public void setName(String name) {this.name = name;}
public String getCapital() {return capital;}
public void setCapital(String capital) {this.capital = capital;}
public Date getIndependenceDay() {return independenceDay;}
public void setIndependenceDay(Date independenceDay) {this.independenceDay = independenceDay;}
public long getPopulation() { return population; }
public void setPopulation(long population) {this.population = population; }
@Override
public String toString() {
return "Country{" + "capital=" + upper-case alphabetic quality + ",
population=" + population + ",
independenceDay=" + independenceDay + '}';
}
public void setIndependenceDay(String date) {
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
this.independenceDay = format.parse(date);
} catch (ParseException ex) {
Logger.getLogger(Country.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]){
Country Republic of Republic of India = new Country("India");
India.setCapital("New Delhi");
India.setIndependenceDay("15/07/1947");
India.setPopulation(1200000000);
System.out.println(India);
}
}
Country Republic of Republic of India = new Country("India");
India.setCapital("New Delhi");
India.setIndependenceDay("15/07/1947");
India.setPopulation(1200000000);
System.out.println(India);
}
}
toString method created past times Netbeans IDE
toString method generated past times Netbeans IDE create next output for to a higher house cast :
toString method generated past times Netbeans IDE create next output for to a higher house cast :
Country{capital=New Delhi, population=1200000000, independenceDay=Fri Aug fifteen 00:00:00 VET 1947}
If you lot hold back at to a higher house output you lot detect that NetBeans does non generated formatted Date for you, instead it calls toString() method of java.util.Date class.
toString() code generated past times Eclipse IDE:
By default Eclipse generates next toString method :
@Override
public String toString() {
return "Country [name=" + advert + ", capital=" + capital
+ ", population=" + population + ", independenceDay="
+ independenceDay + "]";
}
public String toString() {
return "Country [name=" + advert + ", capital=" + capital
+ ", population=" + population + ", independenceDay="
+ independenceDay + "]";
}
You tin generate code for toString method inwards Eclipse past times clicking Source --Generate toString(). It likewise render several options similar choosing code agency e.g. concatenation operator or StringBuffer etc. Here is the output of toString() method nosotros simply created past times Eclipse :
Country [name=India, capital=New Delhi, population=1200000000, independenceDay=Tue Jul 15 00:00:00 VET 1947]
Using ToStringBuilder for overriding Java toString method
Along amongst many useful classes similar PropertyUtils, EqualsBuilder or HashCodeBuilder; Apache park provides about other jewel called ToStringBuilder which tin generate code for toString() method inwards dissimilar styles. Let’s how does output of toString method looks similar inwards uncomplicated agency as well as multi-line style.
Simple Style:
India,New Delhi,1200000000,Fri Aug 15 00:00:00 VET 1947
India,New Delhi,1200000000,Fri Aug 15 00:00:00 VET 1947
Multi-line style:
test.Country@f0eed6[
name=India
capital=New Delhi
population=1200000000
independenceDay=Fri Aug 15 00:00:00 VET 1947
]
NO_FIELD_NAMES_STYLE
test.Country@1d05c81[India,New Delhi,1200000000,Fri Aug 15 00:00:00 VET 1947]
SHORT_PREFIX_STYLE
Country[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]
ToStringStyle.DEFAULT_STYLE
test.Country@1d05c81[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]
Country[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]
ToStringStyle.DEFAULT_STYLE
test.Country@1d05c81[name=India,capital=New Delhi,population=1200000000,independenceDay=Fri Aug 15 00:00:00 VET 1947]
Similarly Google’s opened upwards rootage library Guava likewise render convenient API to generate code for toString method inwards Java.
When toString method is invoked inwards Java
toString is a rather special method as well as invoked past times many Java API methods similar println(), printf(), loggers, assert statement, debuggers inwards IDE, piece printing collections as well as amongst concatenation operator. If subclass doesn't override toString() method than default implementation defined inwards Object cast gets invoked. Many programmers either utilization logging API similar Log4J or java.util.Logger to impress logs as well as oftentimes overstep Object there. logger.info("Customer non constitute : " + customer) as well as if Customer doesn't override toString as well as impress meaningful information similar customerId, customerName etc than it would endure hard to diagnose the problem. This why its e'er practiced to override toString inwards Java.let's encounter about benefits of doing this.
Benefits of overriding toString method:
1) As discussed above, correctly overridden toString helps inwards debugging past times printing meaningful information.
2) If value objects are stored inwards Collection than printing collection volition invoke toString on stored object which tin impress real useful information.One of the classic illustration of non overriding toString method is Array inwards Java, which prints default implementation rather than contents of array. Though at that spot are pair of ways to impress contents of array using Arrays.toString() etc but given Array is an object inwards Java, would bring been much amend if Array know how to impress itself much similar Collection classes similar List or Set.
3) If you lot are debugging Java programme inwards Eclipse than using lookout adult man or inspect characteristic to hold back object, toString volition definitely assistance you.
These are simply about of the benefits you lot acquire past times implementing or overriding toString method inwards Java, at that spot are many to a greater extent than which you lot acquire as well as larn past times yourself. I promise these tips volition assistance you lot to acquire most of your toString implementation. Let us know if you lot whatever unique toString() tips which has helped you lot inwards your Java application.
Further Learning
Complete Java Masterclass
4 ways to compare String inwards Java