In this article, we will discuss String’s toString() method which is used to convert any object into string format, provided an already overridden toString() is present for every object
1. String’s toString() method:
- This String method is used to convert any object into string format
1.1 Method Signature:
public String toString();
1.2 Returns:
- Converts any given object into string, provided an already toString() method is overridden for that object
2. Quick points about toString() method:
- toString() method belongs to Object class
- By default, whenever any object is printed then compiler internally invokes toString() method and prints output in the following format
- ClassName@HashCode_in_HEX_format (i.e.; class-name followed by @ symbol and then hash-code in hexadecimal format)
- To print output in desired format for any object, then toString() method has to be overridden, providing implementation detail
3. Examples on toString() method:
Let’s discuss 2 examples with Employee Object,
- one Employee class without overriding toString() method
- another Employee class overriding toString() method
3.1 Without overriding toString() method
- Let’s see, what exactly gets printed into console
- if toString() method is NOT overridden
- Employee class with 2-attributes
Employee.java
package in.bench.resources.string.methods;
public class Employee {
// member variables
int empId;
String empName;
// getter and setter
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
Test class:
StringToStringMethodTest.java
package in.bench.resources.string.methods;
public class StringToStringMethodTest {
public static void main(String[] args) {
// create 2 employee objects
Employee emp1 = new Employee(1001, "SJ");
Employee emp2 = new Employee(1002, "AK");
// now try to print without overriding toString() method
System.out.println("Employee 1 details : " + emp1);
System.out.println("Employee 2 details : " + emp2);
}
}
Output:
Employee 1 details :
in.bench.resources.string.methods.Employee@1db9742
Employee 2 details :
in.bench.resources.string.methods.Employee@106d69c
From above output,
- it is clear that whenever toString() method is NOT overridden
- then compiler internally invokes toString() method of Object class (which is inherited to our class) and
- prints output hashcode in hexadecimal format following class-name separating @ symbol in between them
3.2 Overriding toString() method
- To convert object into string format
- we need to override toString() method providing implementation detail
- Employee Class with 2-attributes overriding toString() method
Employee.java
package in.bench.resources.string.methods;
public class Employee {
// member variables
int empId;
String empName;
// 2-arg parameterized constructor
public Employee(int empId, String empName) {
super();
this.empId = empId;
this.empName = empName;
}
// getter & setter
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
// overriding toString() method
@Override
public String toString() {
return "Employee [empId=" + empId
+ ", empName=" + empName
+ "]";
}
}
Test class:
StringToStringMethod.java
package in.bench.resources.string.methods;
public class StringToStringMethod {
public static void main(String[] args) {
// create 2 employee objects
Employee emp1 = new Employee(1001, "SJ");
Employee emp2 = new Employee(1002, "AK");
// now try to print without overriding toString() method
System.out.println("Employee 1 details : " + emp1);
System.out.println("Employee 2 details : " + emp2);
}
}
Output:
Employee 1 details : Employee [empId=1001, empName=SJ]
Employee 2 details : Employee [empId=1002, empName=AK]
From above output,
- it is clear that whenever toString() method is overridden then object is printed with all attribute values
Note: at times, toString() method is useful for conversion of wrapper types to String format, as explained in the below articles,
- Java – Integer to String conversion – 6 ways
- Java – Float to String conversion – 6 ways
- Java – Double to String conversion – 6 ways
- Java – Long to String conversion – 6 ways
- Java – Boolean to String conversion – 6 ways
- Java – Character to String conversion – 6 ways
- Java – Character[] array to String conversion – 5 ways
- Java – Byte to String conversion – 5 ways
- Java – Byte[] array to String conversion
- Java – Short to String conversion – 5 ways
- Java – StringBuffer to String conversion and vice-versa
- Java – StringBuilder to String conversion and vice-versa
- Java – String to Date conversion
Hope, you found this article very helpful. If you have any suggestions or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
Related Articles:
- Java – String charAt(int index) method
- Java – String compareTo(String anotherString) method
- Java – String compareToIgnoreCase(String str) method
- Java – String concat(String str) method
- Java – String contains(CharSequence s) method
- Java – String contentEquals(StringBuffer sb) method
- Java – String copyValueOf(char[] data) method (2)
- Java – String endsWith(String suffix) method
- Java – String equals(Object anObject) method
- Java – String equalsIgnoreCase(Object anObject) method
- Java – String format(String format, Object… args) method
- Java – String getBytes() method (4)
- Java – String getChars() method
- Java – String hashCode() method
- Java – String indexOf() method (4)
- Java – String intern() method
- Java – String isEmpty() method
- Java – String join() method (2)
- Java – String lastIndexOf() method (4)
- Java – String length() method
- Java – String matches(String regex) method
- Java – String regionMatches() method (2)
- Java – String replace(char oldChar, char newChar) method
- Java – String replace(CharSequence target, CharSequence replacement) method
- Java – String replaceAll(String regex, String replacement) method
- Java – String replaceFirst(String regex, String replacement) method
- Java – String split(String regex) method
- Java – String split(String regex, int limit) method
- Java – String startsWith(String prefix) method
- Java – String startsWith(String prefix, int toffset) method
- Java – String subSequence(int beginIndex, int endIndex) method
- Java – String substring(int beginIndex) method
- Java – String substring(int beginIndex, int endIndex) method
- Java – String toCharArray() method
- Java – String toLowerCase() method (2)
- Java – String toUpperCase() method (2)
- Java – String toString() method
- Java – String trim() method
- Java – String valueOf() method (9)
References:
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
Happy Coding !!
Happy Learning !!