Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
Members have full access to the forums. Advertisements are removed for registered users.
Hint: What are you returning? What is the return type of the toString method? When you call a standard class's toString() function, does anything print out? Or do you have to print that out yourself?
A valid toString() method would
public String toString()
String str = "Tom";
What you're doing with yours above is basically
public void toString()
Also, it depends what you mean by "valid".
Object has a toString() method that returns a String, but it makes no sense whatsoever unless you're a java compiler (like Eclipse). Also, since Object has a toString(), unless you overload it, you have to have the same parameters, in this case none.
All classes have Object's toString() in them by default and keep it as theirs unless they override it with their own.
An ArrayList will return a toString like this:
[item one, item two, item three, ... last item]
However, it will again make sense only for classes that have a "nice" toString(), like String or Integer for example, otherwise it'll probably use Object's toString(). Overloading is for when you want to have a different parameter, but still have the same return type.
public String toString(String example)
public String toString(String secondExample)
String str = "bob " + secondExample;
Also, for a toString(), often people use them for things like:
public String toString()
String str = "The value is: " + getValue() + ". The name of this item is: " + getName() + ".";
// be careful to use getValue() and getName() and other get methods instead of
// having String str = "The value is: " + value + ". The name of this item is: " + name + ".";
// that may not always produce what you want
// also, make sure that if you have a get method, you call a setMethod() either in your constructor
// or in this toString() method. If in the toString() method itself, make sure to have the value you're
// passing it as a parameter, set Methods have at least 1, sometimes more, parameters, is defined somehow
// inside the method or else it'll say "cannot find symbol". Also, if you don't call the set method, your
// toString() will return "null" for all the get Methods that never called a set method.