Concept
How can the toString() method represent a Java object?
ComputerScienceOne / Common Methods
"The toString() method returns a String representation of the object. However, the default behavior that all classes inherit from the Object class is that it returns a string containing the fully qualified class name (package and class name) along with a hexadecimal representation of the JVM memory address at which the instance is stored. An example with our Student class may produce something like: unl.cse.Student@272d7a10.\n\nWe can override this functionality and change the behavior of the toString() method to return whatever we want. To do so, we simply define the function (with a signature that matches the toString() method in the Object class) in our class.\n\npublic String toString() {\n\nreturn String.format(\"%s, %s (ID = %d); %.2f\",\n\nthis.lastName,\n\nthis.firstName,\n\nthis.id,\n\nthis.gpa);\n\n}\n\nThis example would return a String containing something similar to \"Hamilton, Margaret (ID = 4321); 3.90\". The toString() method is a very convenient way to print instances of your class."
Related Ideas
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- What common methods do Java classes inherit?ComputerScienceOne · Usage
- How does string concatenation work in Java?ComputerScienceOne · String Methods
- What does the completed PHP Student class look like?ComputerScienceOne · Example
- How can you convert a Student structure into a string?ComputerScienceOne · To String Functions
- What is the relationship between equals() and hashCode()?ComputerScienceOne · Composition
- How do member methods differ from static methods?ComputerScienceOne · Accessor & Mutator Methods
- How do you use Java instances and invoke their methods?ComputerScienceOne · Usage