The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Methods with Results

You might have noticed by now that some of the methods we are using, like the Math methods, yield results. Other methods, like println and newLine, perform some action but they don't return a value. That raises some questions:

  • What happens if you invoke a method and you don't do anything with the result (i.e. you don't assign it to a variable or use it as part of a larger expression)?
  • What happens if you use a print method as part of an expression, like System.out.println ("boo!") + 7?
  • Can we write methods that yield results, or are we stuck with things like newLine and printTwice?

The answer to the third question is "yes, you can write methods that return values," and we'll do it in a couple of chapters. I will leave it up to you to answer the other two questions by trying them out. In fact, any time you have a question about what is legal or illegal in Java, a good way to find out is to ask the compiler.

Last Update: 2011-01-24