Timothy Armoo
Timothy Armoo

Reputation: 167

How to properly compile a tostring method

I'm learning java as a beginner so if this question is incredibly trivial, bear with me- we all started from somewhere!

I'm learning about the tostring method and apparently my code below is meant to print out "Hello" however what it is printing out is Ape@6D06d9c which I just dont understand. Could someone please help in explaining where exactly I am wrong and how to remedy it

class Ape {

    public String tostring() {

    return "Hello";
    }
}


public class learningtostring1{
    public static void main(String[] args){
        Ape kermit = new Ape();
        System.out.println(kermit);
}


}

Upvotes: 0

Views: 86

Answers (1)

Shenbo
Shenbo

Reputation: 226

the method you override should be:

public String toString() {
    return "Hello";
}

Java is case sensitive so "toString" is different from "tostring".

A better way to do it is to add a @Override tag on top of your method. Like:

@Override
public String toString() {
    return "hello";
}

If you are not overriding but there is a @Override tag on it then your code would not compile.

By the way what you have printed - "Ape@6D06d9c" used the default toString() method which returns className + "@" + object's hashcode. You can refer to this post for more information on that.

Upvotes: 1

Related Questions