Powered by Blogger.

101 Java - The toString Method Program in Java

Definition of The toString Method:-

The toString() method of Object class convert an object to a String representation, which returns the class name and its reference address. Many classes override toString to provide more useful information.

Syntax:-

        public virtual string ToString()

The toString Method Program:-

 public class TesttoString{
   public static void main(String[]args){
     TesttoString now = new TesttoString();
     System.out.println(now);
     // is equivalent to:
     System.out.println(now.toString());
   }
 }

The toString() method in the Object class is used to display some information regarding any object.
If any code needs some information of an object of a class, then it can get it by using this method

The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method. The following code illustrates this,

ToStringMethodTest.java Program:-

public class ToStringMethodTest {
    private String companyName;
    private String companyAddress;
    public ToStringMethodTest(String companyName, String companyAddress) {
        this.companyName = companyName;
        this.companyAddress = companyAddress;
    }
    public static void main(String[] args) {
        ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
        System.out.println(test);
    }
}

This output seems a bit weird. If we analyze it closely, we can find that the output is nothing but the Class name ToStringMethodTest and then the ‘@’ symbol is followed by 18d107f which is the hashcode of the object.

ToStringMethodTest.java Program:-

public class ToStringMethodTest {
    private String companyName;
    private String companyAddress;
    public ToStringMethodTest(String companyName, String companyAddress) {
        this.companyName = companyName;
        this.companyAddress = companyAddress;
    }
    public static void main(String[] args) {
        ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
        System.out.println(test);
    }

    public String toString() {
        return ("Company Name: " + companyName + "n" +
        "Company Address: " + companyAddress);
    }
}

Remarks:-

ToString is the major formatting method in the .NET Framework. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in the .NET Framework, see Formatting Types.)

The default implementation of the ToString method returns the fully qualified name of the type of the Object, as the following example shows.

using System;

public class Example
{
   public static void Main()
   {
      Object obj = new Object();
      Console.WriteLine(obj.ToString());
   }
}
// The example displays the following output:
//      System.Object

Because Object is the base class of all reference types in the .NET Framework, this behavior is inherited by reference types that do not override the ToString method. The following example illustrates this. It defines a class named Object1 that accepts the default implementation of all Object members. Its ToString method returns the object's fully qualified type name.

using System;
using Examples;

namespace Examples
{
   public class Object1
   {
   }
}

public class Example
{
   public static void Main()
   {
      object obj1 = new Object1();
      Console.WriteLine(obj1.ToString());
   }
}
// The example displays the following output:

//   Examples.Object1

Types commonly override the ToString method to return a string that represents the object instance. For example, the base types such as Char, Int32, and String provide ToString implementations that return the string form of the value that the object represents. The following example defines a class, Object2, that overrides the ToString method to return the type name along with its value.

using System;

public class Object2
{
   private object value;

   public Object2(object value)
   {
      this.value = value;
   }

   public override string ToString()
   {
      return base.ToString() + ": " + value.ToString();
   }
}

public class Example
{
   public static void Main()
   {
      Object2 obj2 = new Object2('a');
      Console.WriteLine(obj2.ToString());
   }
}
// The example displays the following output:
//       Object2: a

Notes to Implementers:-

When you implement your own types, you should override the ToString method to return values that are meaningful for those types. Derived classes that require more control over formatting than ToString provides can implement the IFormattable interface. Its IFormattable.ToString(String, IFormatProvider) method enables you to define format strings that control formatting and to use an IFormatProvider object that can provide for culture-specific formatting.

ToString Returning a Null Reference:-

While the practice of overriding the ToString method to return a null reference is not prohibited, I would strongly discourage it.

The ToString method is designed to return a meaningful string representation of an object, and one that serves to identify the object. Where possible, it should return a string representation of the object's value (as is the case with strings, numbers, and dates). If that's not possible or desireable, it should return a string indicating the object's type (as is the case with collection objects, for example, or with the default implementation of the Object.ToString method).

For formatting operations, there's no particular harm in returning a null reference, since an attempt to use the returned null string in a formatting operation simply produces an empty string. For example, If null_String is a null string, the statement Console.WriteLine(nullString) results in an empty string being displayed to the console. Similarly, the statement String.Format("{0}", null_String) returns an empty string.

The major problem arises when attempting to call instance methods on the null string, since these method calls will always throw a NullReferenceException. And since a string returned by a call to an object's ToString method is assumed to be valid (that is, non-null), it's unlikely that developers who consume the type will check to see whether the string returned by ToString is non-null before calling its instance methods.

0 comments:

Post a Comment