Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Harnessing the Power of Objects Changing State

Wan Nor Adzahari Wan Tajuddin
Wan Nor Adzahari Wan Tajuddin
2,438 Points

What does it mean when we are making sure that the method doesn't return anything (by using void) ?

If I don't use void, I will fail the question because I have to make sure that the method isn't return anything. What actually is meant by "return" ? Does a method always meant to return something?

GoKart.java
class GoKart {
  public static final int MAX_BARS = 8;
  private String color;
  private int barCount;

  private void charge() {
    barCount = MAX_BARS;
  }

  public GoKart(String color) {
    this.color = color;
  }

  public String getColor() {
    return color;
  }
}

1 Answer

andren
andren
28,558 Points

A method does not have to return something, but all methods need to have a return type. The return type tells Java what type of value it can expect the method to return, the void type is just there to tell Java that the method does in fact not return anything.

Returning a value simply means that the method basically sends a value back to the code that called it after it is done running, using the return keyword. Let's say you created a method to pick a random item from some list as an arbitrary example. If the method choose an item but had no way of actually telling you what item it ended up choosing, it would be pretty pointless to call the method.

Returning values is a pretty fundamental part of Java programming, so it's something you'll see plenty of example of through the courses. So even if you don't fully understand it right now you'll get plenty of examples to look at and time to practice with it.

Wan Nor Adzahari Wan Tajuddin
Wan Nor Adzahari Wan Tajuddin
2,438 Points

I think your explanation cleared up some of the haze here. Thanks!