ToString function

What is the default value for toString() in java? Explain me with an example?

Questions by sandyl2   answers by sandyl2

Showing Answers 1 - 16 of 16 Answers

javagek

  • Aug 30th, 2011
 

The default implementation of toString method in Object class returns the fully qualified name of the object's class followed by an '@' sign and a reference id that points to the object. E.g.

Object objTemp1 = new Object();
System.out.println("OBJECT :" + objTemp1.toString());

would print something like OBJECT :java.lang.Object@19821f on the console.

Note, the value of id might change every time your run the program.

  Was this answer useful?  Yes

Nikhil

  • Feb 21st, 2013
 

If toString() method is not overriden, it will return

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This is Object version of this method.

  Was this answer useful?  Yes

Default value is String representation of any Object.

Code
  1. class Student {

  2.  int rollNo;

  3.  String name;

  4. public Student(int rollNo, String name){

  5. this.rollNo = rollNo;

  6. this.name = name;

  7. }

  8. }

  9. class StringEx {

  10.        Student s1= new Student(1,"sandy");

  11.        System.out.println(s1);

  12. }

  13.  


Output :: Student@1f231e

Here the output is Name of the Object class i.e Stundent and hashcode of that object i.e 1f231e ..... If you observe the above code, we are calling the s1 object in System.out.prinln ......But internally it calls the toString method which is present in Object class. So the above output given by Object class toString method.

If you want then you can override that function in Student class as given below

Code
  1. class Student {

  2.  int rollNo;

  3.  String name;

  4. public Student(int rollNo, String name){

  5. this.rollNo = rollNo;

  6. this.name = name;

  7. }

  8. public String toString(){

  9.  return rollNo+ " " +name;

  10. }

  11. }

  12. class StringEx {

  13.        Student s1= new Student(1,"sandy");

  14.        System.out.println(s1.toString());

  15. }


Output :: 1 sandy


Please observe the code difference in above two programs then you can understand very easily.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions