Why calling Java Object Instance executes method of object [duplicate] - java

This question already has answers here:
when to use toString() method
(9 answers)
Closed 6 years ago.
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;
}
}

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());
}

"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~)

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());

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.

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.

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.

Related

Printing without calling method [duplicate]

This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 4 years ago.
it may seem as a very basic question, but I do not understand why the method toString is printed on the screen when I didn't even called it, I just instantiated a Car object. Thanks
public class Car {
public void m1() {
System.out.println("car 1");
}
public void m2() {
System.out.println("car 2");
}
public String toString() {
return "vroom";
}
}
public static void main(String[] args) {
Car myCar = new Car();
System.out.println(myCar);
}
The String.valueOf(Object) method is called implicitly, see the doc of println(Object x):
Prints an Object and then terminate the line. This method calls at
first String.valueOf(x) to get the printed object's string value, then
behaves as though it invokes print(String) and then println().
and the doc of String.valueOf(Object obj):
if the argument is null, then a string equal to "null"; otherwise, the
value of obj.toString() is returned.
Because there's no System.out.println(Car) method, the Java compiler picks the closest match it can, which is System.out.println(Object). That calls String.valueOf on what you pass in to get the string version of it to print. String.valueOf uses the toString method of your object to get the string. From its documentation:
Returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
In this line System.out.println(myCar) the toSring method is internally called because println calls at first String.valueOf(myCar) to get the printed object's string value. valueOf uses myCar.toString() if myCar is not null.
So the full flow would be like this:
System.out.println(myCar) > String.valueOf(myCar) > myCar.toString()

Difference between wrapper class reference and user defines class reference in java

Suppose I have a custom class, say Test.
Test test = new Test(); // test is the reference.
Now when I print the value of test, it returns the hashcode .
Now consider,
Integer i = new Integer(10);
When I print the value of i, it returns 10.
Can someone help me to understand what exactly is the difference here? I believe both are object references, but for wrapper class reference, it returns the value of the object it is pointing to.
When you create a new class, it inherits the method toString() from Object. Integer class overrides that method to return the inner value.
When printing, there is an implicit call to toString() method.
By default (in for your Test class) it uses the one inside Object class. For Integer, it convert the Integer to a String in 10-base.
Your Test class is using Object class's toString() method which prints hashCode. But for Integer class, toString method is overrided. You can see Integer.java here
user defined reference is an object,if you print that object means you may get some hash code because every class extends Object class,so your also have the property (method) tostring().
Wrapper class wraps its respective primitive data type
Integer i = new Integer(10);
and
i=10;
both same in value.
When you call System.out.println(Object) (or, more generally, PrintStream.println(Object)):
This method calls at first String.valueOf(x)
String.valueOf(Object) returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Neither of your objects are null, so the toString() method of the instances is called.
In the case of Integer:
The value is converted to signed decimal representation and returned as a string
In the case of Test, unless you've explicitly overridden it (or a superclass has overridden it), you will call Object.toString():
[T]his method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
If this isn't the desired behaviour, override toString() in Test:
class Test {
#Override public String toString() {
// ... Your implementation.
}
}
Whenever you print the object Java will invoke the toString() method. The default implementation of toString() available in Object Class. Object is the base class for the all the Object in java.
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
It will print the class Name with full package path # and HashCode of the object.
The test class doesn't override the toString() method. But all the wrapper class in java override the toString().so when You invoke the Integer method it invoke the toString() implemented in Integer class.

The connection between 'System.out.println()' and 'toString()' in Java

What is the connection between System.out.println() and toString() in Java? e.g:
public class A {
String x = "abc";
public String toString() {
return x;
}
}
public class ADemo {
public static void main(String[] args) {
A obj = new A();
System.out.println(obj);
}
}
If main class runs, it gives an output as "abc". When I remove the code which overrides toString(), it gives an output as "A#659e0bfd". So, can anyone explain what is the working principle of System.out.println() when I pass the obj object reference as an argument to it? Is it fully connected with toString() method?
System.out is a PrintStream. Printstream defines several versions of the println() function to handle numbers, strings, and so on. When you call PrintStream.println() with an arbitrary object as a parameter, you get the version of the function that acts on an Object. This version of the function
...calls at first String.valueOf(x) to get the printed object's string value...
Looking at String.valueOf(Object), we see that it returns
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, long story short, System.out.println(someObject) calls that object's toString() function to convert the object to a string representation.
If your object defines its own toString() function, then that is what will be called. If you don't provide such a function, then your object will inherit toString() from one of its parent classes. In the worst case, it will inherit Object.toString(). That version of toString() is defined to return
a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object.
Or, in other words:
getClass().getName() + '#' + Integer.toHexString(hashCode())
So, when you call System.out.println() on an object that doesn't define its own version of toString(), you might get the Object version which looks like "classname#someHexNumber".
toString() is a method that exist in the Object class (Root of the inheritence tree) for all classes.
System.out.print() (SOP) will call the toString method when fed an object.
If you don't overwrite the method toString(), SOP will call the parent toString() which, if parent is the Object class, it will print the hashCode of the object
If you overwrite the method, SOP will call your toString() method
System.out.println(obj) will print the returned string from obj.toString() if you dont override it it will call the base object.toString() method which by default the toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', 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())

How an object will call toString method implicitly?

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
You're not explicitly calling toString(), but implicitly you are:
See:
System.out.println(foo); // foo is a non primitive variable
System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As we see, it's calling the String.valueOf(Object) method.
This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString() is called.
Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.
Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.
even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)
printing an object using println()
printing a Collection of objects (toString() is invoked on all the elements)
concatenation with a String (like strObj = "My obj as string is " + myObj;)
Everything inherits from Object, so the toString on Object will be called if you have not defined one.
toString() method is present in Object class, so when u put obj in System.out.println(obj);, impliciyly it will call toString() present in Object class since every user created class will implicitly inherits Object class so as ur newly created class, that means that toString() is available in ur class so it will print something like for example: "PkgNamePackage.Classname#12cf4"
However if u explicitely override toString method and give ur own implementation then it will written the string what ever u give in Overriden tostring method();
ex:
public class DogArray {
#Override
public String toString() {
return "Im the newly created Object";
}
public static void main(String args[]) {
DogArray d1 = new DogArray();
System.out.println(d1);
}
}
output: Im the newly created Object
In java object class is super class to the each and every class.whenever your passing parameter to the system.out.println internally object class to string method will be excuted.it returns class name#reference value given but as per our application requirement object class to string method will override in collection and string class.it returns their content.

Java Link list error message when executed #number

Whenever i run the method, i get an error which comes with as numbers
The following is what i have as my code.
public String getAccount()
{
String s = "Listing the accounts";
for(List l:lists)
s+=" "+list.toString;
Return s;
}
I get the following when i run this method:
List#some numbers
For the List class, i just have a constructor which appoints parsed variables into local variables.
DOes someone know what this means?
This means that you haven't overridden the toString method in your (apparently) custom List class. The default implementation (Object.toString) displays output like you show above:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', 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())
You should override toString in your custom classes, in order to provide the desired output.

Categories