FAQ: Learn Java: Methods - The toString() Method

This community-built FAQ covers the “The toString() Method” exercise from the lesson “Learn Java: Methods”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Java

FAQs on the exercise The toString() Method

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

1 Like

I don’t understand how System.out.println knows to connect with the toString method. What would we do if we had several classes that we wanted to print different messages about in main()?

7 Likes

When we print out Objects, we often see a String that is not very helpful in determining what the Object represents. In the last lesson, we saw that when we printed our Store objects, we would see output like:

Store@6bc7c054

where Store is the name of the object and 6bc7c054 is its position in memory.

This doesn’t tell us anything about what the Store sells, the price, or the other instance fields we’ve defined. We can add a method to our classes that makes this printout more descriptive.

When we define a toString() method for a class, we can return a String that will print when we print the object

so the toString method is useful to see what an object represents, what you want would require defining methods to call on the object.

Is toString a reserved word? What would have stopped me inadvertently making a toString() method to do something entirely different, only to find out that it was invoked when I tried to print the object?

2 Likes

some things are the the developers responsibility, as developer you are mostly in control, so nothing would have stopped you

its an existing method yes, which you just overwrote for this object

toString is always invoked when printing an object.

4 Likes

How does control passes to toString() method from main since we haven’t called it exclusively.

its explained nicely here:

https://www.javatpoint.com/understanding-toString()-method

java calls toString automatically when you print an object.

7 Likes

I copied the solution to atom, and when I compile it I get the error : invalid method declaration; return type required
public Store(String product, double initialPrice)

Any idea why? It runs fine on the website?

The only way I could reproduce this error was by having store in lowercase on the constructor.

  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }

The above doesn’t raise a error.

Hi all. What exactly am I doing wrong here?

can someone help me understand why it says I completed the lesson yet I still have an error

i think the the closing curly bracket on line 36 closes the class, so the curly bracket on line 37 needs to removed. You have would have to verify.

Difficult to say for sure, given i can’t see the full code and the code isn’t perfectly indented.

You’re only supposed to print out lemonadeStand

Why the output of this program contains null? what is the problem?

public class Car {
	//Instance fields
	String color;
	int topSpeed;
	String carModel;
	
	//constructor method
	public Car(String carColor, int maxSpeed, String typeCar) {
		carColor = color;
		maxSpeed = topSpeed;
		typeCar = carModel;
	}
	
	public String toString() {
		return "This is a "+ color + " " + carModel + " with a top speed of " + topSpeed; 
	}
	
	public static void main(String[] args) {
		
		Car buggati = new Car("blue", 500, "buggati");
		Car lamborghini = new Car("black", 400, "lamborghini");
		
		System.out.println(buggati);
		System.out.println(lamborghini);
		
	}
}

in the constructor, you assign the instance fields (which are null) to the parameters of the constructor, why?

1 Like

Thanks XD, I get it now what you meant , and it fixed the issue. Many thanks :pray:

Hi! Is there anytime we would want to keep displaying the memory and class name, and if so, could we do it even if we had changed the toString() method?

Thank you. This answered my question too. It would be nice if this link was included somewhere in the lesson

1 Like

"its an existing method yes, which you just overwrote for this object

toString is always invoked when printing an object."

Thank you. that was an important piece of information that was missing for those of us not trying to just memorize everything but to understand the hows and whys.

1 Like

flip801 is wrong, the step clearly states you need to print out both lemonadeStand and cookieShop.
I can’t tell what you’ve done wrong, the screenshot may be too cropped and it’s hard to tell if you maybe used the wrong character. However this is my answer and it was correct:
image