0

I've been learning Java currently and am confused about a certain piece of code. I come from a C, Python background, so I'm more learning the syntax and small niches of Java.

Below I have 2 classes. My Main class and a class that contains a method to return the decorated input string of the class.

I'm confused as to why calling myObject automatically calls the "toString()" method which returns the message? Shouldn't I need to define the method I want to call on the object? Why can you do this in Java?

I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location.

Any help would be great. Thanks!

public class HelloWorld
{
  public static void main(String[] args)
  {
    int i = 0;
    OtherClass myObject = new OtherClass("Hello World!");
    // This calls method toString()
    System.out.print(myObject);

    // This calls method toString()
    System.out.print(myObject.toString());
  }
}

public class OtherClass
{
  private String message;
  private boolean answer = false;
  public OtherClass(String input)
  {
    message = "Why, " + input + " Isn't this something?\n";
  }
  public String toString()
  {
    return message;
  }
}
Sam
  • 457
  • 2
  • 6
  • 21
  • Maybe I didn't understand the question but the method System.out.print() wants a String as a parameter and, passing it an object, it automatically calls the toString() method of that object. – Robert Kock May 24 '16 at 07:21
  • Please check this [link](http://stackoverflow.com/questions/29318996/the-connection-between-system-out-println-and-tostring-in-java) It might help you with your query. – greenPadawan May 24 '16 at 07:22
  • `print(myObject)` is not "calling" the object. It is passing a reference to the object to the `print` method. Now, the `print` method will then call the `toString()` method of the object, because that is what `print(Object)` has been coded to do. – Andreas May 24 '16 at 07:27
  • `System.out.print(myObject)` is _implemented_ as `System.out.print(myObject.toString())`. If you looked up the implementation of `System.out.print` and traced through the code you'd find `myObject.toString()` in there. – Louis Wasserman May 24 '16 at 18:22

6 Answers6

2
public void print(Object obj)

Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

And as @Andreas said in the comments, toString() prints the hashcode if this method isn't overridden by the subclass:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Community
  • 1
  • 1
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • `obj` will print the memory location of **object** not the object – bananas May 24 '16 at 07:29
  • 1
    @holidayCoder The `print` method will result in `toString()` being called. If that hasn't been implemented by the class, the default implement in `Object` is called, which print the class name and a **hash code**, not a memory address. If `toString()` has been implemented by the class, you very likely will not see the hashcode printed. – Andreas May 24 '16 at 07:31
  • @Andreas What does the hash code mean? What does it represent? – Sam May 24 '16 at 07:53
  • 1
    @Sam https://en.wikipedia.org/wiki/Java_hashCode%28%29 – Andreas May 24 '16 at 16:54
0

This is a build in feature in java. You dont need to write .toString() to print information about the Object.

You can use this feature everywhere, even with java operators:

System.out.print(myObject1 + myObject2);

is the same like:

System.out.print(myObject1.toString() + myObject2.toString());

toString() is a method in java.lang.Object, so every object contains this method. The default implementation displays the hashcode. You can override it with your own implementation.

tak3shi
  • 2,305
  • 1
  • 20
  • 33
  • Actually, `myObject1 + myObject2` is the same as `new StringBuilder().append(myObject1 ).append(myObject2).toString()`. It is the `append` method that ends up calling `toString()`. – Andreas May 24 '16 at 07:29
0

in Java there is a class that called Object, any other classes that you define

inherit from that , it has a method named 'toString'

/** * Returns a string representation of the object. In general, the * {@code toString} method returns a string that * "textually represents" this object. The result should * be a concise but informative representation that is easy for a * person to read. * It is recommended that all subclasses override this method. *

* The {@code toString} method for class {@code Object} * returns a string consisting of the name of the class of which the * object is an instance, the at-sign character `{@code @}', and * the unsigned hexadecimal representation of the hash code of the * object. In other words, this method returns a string equal to the * value of: *

*
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * 
* * @return a string representation of the object. */

So you can simply run your main method in debug mode and set a break point

in toString of Object

 System.out.println(new Object());
Moolerian
  • 534
  • 6
  • 18
0

If you want to represent any object as a string, toString() method comes into existence.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

Khan Abdulrehman
  • 816
  • 2
  • 10
  • 22
0

Java was designed to easily print objects as strings.

System.out is a PrintStream (see https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#print-java.lang.Object-)

When you pass an object to the method print (or println), you're actually calling

String.valueOf(Object) (see https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#valueOf-java.lang.Object-)

Which in turn will do the following

"if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned."

If your object has an explicit toString() implementation, this method will be called, otherwise the interpreter will try to find an object in the hierarchy that implements it.

Leo
  • 751
  • 4
  • 29
0

"I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location."

In fact, the method which holds the same name as the class(OtherClass for example) is the constructor method, which will be called automatically when you initialize the class.

In this case, when you run OtherClass myObject = new OtherClass("Hello World!");, the constructor method

public OtherClass(String input)
{
    message = "Why, " + input + " Isn't this something?\n";
}

is called and set message value. And when it comes to System.out.print(myObject);, myObject.toString()will be called and return String message.

So the key point here is to override toString() method in your class, you may print whatever message you want by modifying toString()method, if this method is not override, it will return something associate with hashcode. (Just try and enjoy~)

elricfeng
  • 364
  • 1
  • 8
  • 1
    To clarify: You should never "print" in the `toString()`. You should return the appropriate string, and it is up to the caller to print, or do whatever is needed. – Andreas May 24 '16 at 16:56