Difference between wrapper class reference and user defines class reference in java - 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.

Related

What happens to println() when object is passed

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

Object.toString() does not return the hashcode value of the object in java but instead give some string

I have written the following code:-
Test ob = new Test();
System.out.println(ob.toString());
System.out.println(ob.hashCode());
and the output is
Test#15db9742
366712642
i understand that the second value is the hashcode of the object and it is an integer value but i am not able to understand what is the first value. If it is the hashcode of the object then how can it be string and not integer
If you read the docs for toString very carefully:
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())
366712642 in hex is exactly 15DB9742!
If it is the hashcode of the object then how can it be string and not integer?
As you can see from the docs, it is the class name, plus #, plus the dashcode, not just the hash code. Also, the method's name is toString. It would be weird if it returned an int, wouldn't it?
It represents classname#HashCode_in_Hexadeciaml_form. So, the string which you are seeing is actually the hexadecimal form of the integer hashcode
You can look the source code of Object.java. toString method is meant to provide information about class at runtime, so can be overriden. What you're doing is calling the default toString method from Object.java. It simply returns following:
getClass().getName() + "#" + Integer.toHexString(hashCode()
Hence the output.
See code here

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

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.

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.

Categories