What happens to println() when object is passed - java

Circle c = new Circle(colour, radius);
System.out.println(c);
Consider a class Circle now what will the println statement do when we have toString() method in class Circle and when we do not have one.

toString() is a method of Object class and this class is superclass of all classes (if you create a new class, that extends no other class, it will implicitly inherit from Object class. Remember that Java does not support multiple inheritance i.e class can have only one direct superclass). If you override toString() in inheriting class then your implemnentation will be called by System.out.println() implicitly. If you do not override this method, also toString() will be invoked but with default implementation from Object class. And the default implementation of Object::toString returns :
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())

Related

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

hashCode method called for System.out.println() method in HashSet

import java.util.HashSet;
import java.util.Set;
class Employee {
#Override
public int hashCode() {
System.out.println("Hash");
return super.hashCode();
}
}
public class Test2 {
public static void main(String[] args) {
Set<Employee>set= new HashSet<>();
Employee employee = new Employee();
set.add(employee);
System.out.println(set);// if we comment this "Hash" will be printed once
}
}
Above code calls hashCode method 2 times if we print set. Why hashcode method is called on System.out.println()?
Find the following reason for printing Hash two times
For finding the hash value when you insert the Employee into the HashSet
When you print the set, it's calls the hashCode() method inside the default toString() method from Object class.
The default toString() method from Object class API docs says
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())
See this. In short, the default toString() function calls hashCode() and uses a hexadecimal representation of the hash as part of the String.
The first call to hashCode() is executed when adding an Employee to your set variable, as it's needed in order to calculate which bucket to put it in.
The second call is a bit sneaker. Any Collection's default toString() is a coma-delimited concatination of all its elements toString()s enclosed by square brackets (e.g., [object1, object2]). Any object's default toString(), if you don't override it is getClass().getName() + "#" + Integer.toHexString(hashCode()). Here, since you don't override Employee's toString(), it's called again when you print set.

confusion in inheritance - value of "this" when printed in constructor

I have the following code.
class Test {
int i = 0;
Test() {
System.out.println(this);
System.out.println(this.i);
}
}
public class Demo extends Test {
int i = 10;
Demo() {
super();
System.out.println("calling super");
System.out.println(this);
System.out.println(this.i);
}
public static void main(String[] args) throws IOException {
Demo d = new Demo();
}
}
O/P : Demo#2e6e1408
0
calling super
Demo#2e6e1408
10
When I execute the program and print the value of "this", in both super class constructor as well as in child class constructor, the value of this (address location) is displayed as childClassName#someValue .. My question is, why dont I get the value of Test i.e, Test#someVal (Super class) when I print value of "this" in the super class.. ASAIK, Super class will also have a place/location in memory, so, why am I not getting Test#someValue in the first SOP...
PS : I know variables are referenced based on the reference type (LHS) and methods are called based on the object type (RHS)..
When I execute the program and print the value of "this", in both super class constructor as well as in child class constructor, the value of this (address location)...
The output of System.out.println(this) with the default Object#toString is not the address of the instance in memory. It's just the name of the class and the instance's hash code, nothing more. From the documentation:
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())
It's true that the hashCode documentation says
This is typically implemented by converting the internal address of the object into an integer...
but it also says
...but this implementation technique is not required by the JavaTM programming language.
...and of course the JVM is free to move instances around in memory as necessary, but isn't allowed to change the hashCode.
...why dont I get the value of Test i.e, Test#someVal (Super class) when I print value of "this" in the super class.
There is one instance. That instance is of the subclass. When you do System.out.println(this), it doesn't matter whether you do that in the base class or the subclass, it's still the same object instance you're using. That one object has features it gets from the subclass and also features it inherits from the superclass, but there aren't two separate instances; there's one instance with a combined set of features. super isn't an object reference, although it looks a bit like one; it's a syntax mechanism for specifically asking the compiler to use a feature the instance inherits from the superclass rather than the equivalent feature of the instance (in case they're different).
Demo is a composition of 3 classes: itself, Test and Object. But an instance of Demo is one object, in memory it consists of fields of its super class + its own fields: Test.i + Demo.i (Object has no fields).

Java: f21.Person#373ee92

f21.Person1#373ee92
Ok the f21 represents the package.
Person the class type.
Can anyone explain in simple terms WHY there is an "#" followed by random characters. And what the random chars stand for (position in the memory?).
I receive this when I do the following and HAVEN't declared a toString() method:
System.out.println(myObject);
If you dont Override the toString() method in your class, Object class's toString() will be invoked.
System.out.println(myObject);// this will call toString() by default.
Below is the Implementation of toString from java.Lang.Object class.
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
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
so, apply the same to21.Person#373ee92:
21.Person(Fully qualified classname) + # + 37ee92(hex version of the hasgcode)
It invokes toString() implementation, if you haven't overriden this method then it will invoke Object's version which is implemented as follows
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
It is hex version of hashcode of that instance
If you don't override the toString() method, the one provided by Object is used. It does the following:
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())
The "random" characters are the hash code of your object, in hex.

Categories