Class method called by only presenting object name - java

I have the following piece of code
public class DriverTester {
public static void main(...){
// test empty constructor
Person p1 = new Person();
System.out.println("p1: " + p1);
}
}
public class Person {
private String name;
// Empty constructor
public Person () {
}
// getter avoided for simplicity
public String toString() {
return "Mr.or Ms. "+this.name;
}
}
It compiles, runs succesfully and shows "Mr or Mrs null". So, that would b e the result of calling the toString method.
I don't understand the syntax in of the print line method. How is it that simply the name of the object p1 runs a given method. How does it know which method to run? Shouldn't the syntax be
System.out.println("p1: " + p1.getName());
or
System.out.println("p1: " + p1.toString());
Thanks for any clarification

When concatenating strings, such as in this line:
System.out.println("p1: " + p1);
Java will call the toString() method to convert any object to a String for concatenation. Java ensures that this method exists on all objects, because it's defined on the Object class, which every class implicitly inherits from.
Additionally, if a null is concatenated, then Java will convert that into the String "null".
The Java Language Specification, section 5.1.11, covers "String Conversion":
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but
if the result of invoking the toString method is null, then the
string "null" is used instead.

PrintStream used by System.out.println uses String.valueOf
649 public void print(Object obj) {
650 write(String.valueOf(obj));
651 }
which in turn uses the Object's toString method provided the Object itself is not null, otherwise the literal "null" is returned.
2837 public static String valueOf(Object obj) {
2838 return (obj == null) ? "null" : obj.toString();
2839 }

Related

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.

Understanding java compiler

Assuming I have this two classes, in separate files:
public class Text
{
public String _word;
public Text(String w)
{
_word = w;
}
public String getWord()
{
return _word;
}
public boolean equals (Text other)
{
return ((other!=null)&&(_word.equals(other._word)));
}
public boolean test (Text other)
{
return 1==1;
}
}
2nd class:
public class Sentence
{
public String _word;
public Sentence(String w)
{
_word = w;
}
public String getWord()
{
return _word;
}
public boolean equals (Object other)
{
return ((other!=null) && (other instanceof Sentence)
&& (_word.equals(((Sentence) other)._word)));
}
}
And the following main:
public static void main(String[]args){
Text y1 = new Text("abc");
Sentence z1 = new Sentence ("abc");
**
}
Let's say I run the following command where ** is:
System.out.println (y1.equals(z1));
Everything is ok, and it outputs "false".
But, if I run this command:
System.out.println (y1.test(z1));
The compiler screams "Sentence can not be converted to Text".
Two questions:
Why it works for equals but not for test? y1 is Text, so calling y1.equlas() calls to equlas() inside Text, and there it gets only Text as parameter.
If it DOES work, why the output is false? both "_word" set to "abc".
Thanks!
You've defined an equals(Text) method in Text. However, it doesn't override the existing equals(Object) method that it inherits from Object. Because of this, your equals(Text) method overloads the equals(Object) method in Object. Consequently, you can call y1.equals(z1). Because z1 is a Sentence, the equals(Object) method is the one called. The Sentence object matches Object but not Text. The equals method in Object compares object references to see if they're identical.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
They're not, so it returns false.
You've defined a test(Text) method in Text. There are no other overloads available, and Sentence doesn't match Text at all, so the compiler complains.
Incidentally, the equals(Object) method you've defined in Sentence is a proper override of equals, checking for null and the class of the argument.
According to the Object class definition, you inherit this in all classes
public boolean equals(Object obj)
In your case y1.equals(z1) is actually executed as y1.equals( (Object) z1), a valid cast since all objects inherit Object. You then have the above method called.
I think in Text.java you wanted to override Object.equals(Object other), but instead of overriding you created an other method with the same name (equals(Text other)), but with different parameter type.
That is why System.out.println (y1.equals(z1)); compiles: that equals call matches the signature equals(Object), which method Text inherits from Object.
On the other hand, System.out.println (y1.test(z1)); fails to compile, since Text has only 1 method with the name test, and its formal parameter type is Text, which doesn't match the type of the actual parameter (Sentence).

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.

How to print all the elements from a ArrayList?

I'm trying to print all the element I have added to my arraylist, but it only prints the adress and not the string.
Can someone help me or give out some tips? I've been searching all afternoon
You need to override Autuer's toString method to return its contents in String format
You can also, use a foreach to do it ;)
for(Auteur a: auteurs){
System.out.print(a.getName() + " - " + a.getNumber());
}
itr.next() returns object of Auteur rather than String. To print the name you need to type cast it with Auteur and then print it if you have a print method for the class Auteur.
Auteur aut = (Auteur) itr.next();
System.out.println(aut.printMethod());
Try defining the toString() method in your Auter class as follows:
public String toString() {
return this.getName() + " - " + this.getNumber());
}
and your code will do what you wish. System.out.println calls the argument's toString() method and prints that out to the Output console.
Every object in Java inherits
public String toString();
from java.lang.Object
in your Auteur class you need to write some code similar to the following:
....
....
#Override
public String toString() {
return "Name: "+this.name;
}
What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
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())
We can override toString to give a more human readable output. Take a look at the below two classes, with and without toString. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
#Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}

Get Object from reference Id

is it possible to get an object from his reference id?
i get a list of String containing the reference id of an object like:
com.test.test.business.model.Gamma#20
how to get the object from this reference id?
it's only a string and it isn't castable to the object itself
What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
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())
In short, you can't get an object using this reference id.
We can override toString to give a more human readable output. Take a look at the below two classes, with and without toString. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
#Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}
However, if you are really looking for a way to persist objects and resurrect them at a later stage, you should read up on Serialization.

Categories