Quick Reach
The toString method
The Java toString is a String class method. This method returns an object’s string representation.
A few points about the toString method are:
- The toString method returns a string.
- The string contains the name of the class of object.
- Returned string also contains an ‘@’ sign along with the unsigned hexadecimal representation of the hash code of the object.
- It is recommended that all subclasses override this method.
- By overriding, the value of the object can be returned.
To make it clear, see the example below and especially output with and without the toString method.
Example without toString method
See this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
package test_package;
public class string_example {
String name;
int age;
string_example(String name, int age){
this.name=name;
this.age=age;
}
public static void main(String []args) {
string_example str1=new string_example(“Mike”,30);
System.out.println(str1);
}
}
|
The output is:
test_package.string_example@64c3c749
As you can see, this is not understandable output with hash code without using the toString method.
To get the value of object, let us use the toString method as follows..
Example with Java toString method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public class string_example {
String name;
int age;
string_example(String name, int age){
this.name=name;
this.age=age;
}
public String toString(){//overriding the toString() method
return “Name is:” +name +” age is:” +age;
}
public static void main(String []args) {
string_example str1=new string_example(“Mike”,30);
System.out.println(str1);
}
}
|
See the example online
The output is:
Name is:Mike age is:30
As you can see, this outputs understandable result by using the toString Java.
Also see Java string
Leave A Comment?