The toString() method of Object in Java

This is explained in the API
toString
Public String to String () returns the string representation of the object. Typically, the toString method returns a string that "textually represents" the object. The result should be a concise but readable expression of information. It is recommended that all subclasses override this method.
The toString method of the Object class returns a string consisting of the class name (an instance of the class is the object), the at tag "@" and the unsigned hexadecimal representation of the object hash code. In other words, this method returns a string whose value is equal to:
getClass().getName() + '@' + Integer.toHexString(hashCode())
Return:
The string representation of the object.

/*public String toString();Returns the string representation of the object
 * 
 * 
 * getClass().getName() + '@' + Integer.toHexString(hashCode())
 * 
 * Integer A Static Method under Class
 * public static String toHexString(int i):Converting an integer to a string in hexadecimal representation
 * 
 * Now it's meaningless, so it's recommended that subclasses override this method, which can be automatically generated by returning all the member variable values of the class.
 */
public class ToStringTest {
	public static void main(String[] args) {
		teacher t2 = new teacher();
		teacher t3 = new teacher();
		System.out.println(t2);
		System.out.println(t3);
		System.out.println("-----------------");
		System.out.println(t2.hashCode());//366712642
		System.out.println(t2.getClass().getName());
		System.out.println("-----------------");
		System.out.println(t3.hashCode());//1829164700
		System.out.println(t3.getClass());
		System.out.println("-----------------");
		System.out.println(t2.toString());
		System.out.println(t3.toString());
		System.out.println("-----------------");
		System.out.println(t2.getClass().getName()+'@'+Integer.toHexString(t2.hashCode()));
		System.out.println(t2.toString());
	}

}
class teacher{
	private String name;
	private int age;
	public teacher(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public teacher() {
		super();
		// The constructor stub automatically generated by TODO
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	//@Override
	//public String toString() {
		// Method stub for TODO automatic generation
	//	return super.toString();
		//return "hello";
	//}
	@Override
	public String toString() {
		return "teacher [name=" + name + ", age=" + age + "]";
	}
	
}


Posted on Tue, 08 Oct 2019 01:12:56 -0700 by Neotropic