Choosing between 'return' and 'System.out.println()'

In the Build a droid -exercise, we are asked to create these two methods:

public void performTask(String task) {
    batteryLevel = batteryLevel - 10;
    System.out.println(name + " is performing task: " + task);
  }

  public String toString() {
    return "Hello, I'm the droid: " + name;
  }

On the surface, they appear to do very similar things. When called upon from an instance, they both print out lines that combine strings and variables.

What I can’t wrap my head around is how do you know when to use return or System.out.println? What is the difference? Why is it called void when it does in fact print out a line? There were some threads in the forum that touched the subject but didn’t explain it so that I could understand. What does return do that printing doesn’t?

On a side note: The Codecademy courses are the best resource I’ve found for learning to code by myself, but sometimes there’s this sense of “just type in this to make it work”, without really explaining the larger context of why you do things or how to choose between things. Such as, why does one of the above constructor methods need “stuff” inside the parentheses performTask(String task) and the other works just fine without it toString()? What other words could you put instead of public? Why do you declare variables “inline” in a class, when separation is practised for things like CSS stylesheets?

1 Like

So, in general, ‘return’ does not print something out from a function. Only System.out.println does that.

If you call toString, it will return whatever you have in the return value of that function.

As far as ‘void’, void means it has no return value. It doens’t say anything about whether or not it prints something. In your example, performTask returns nothing, so the return type is void. It has no return statement.
toString has a return statement, and the thing in the return statement is string, so the type is string.

1 Like