Chapter 3 Methods
In Chapter 2 Values, variables, and expressions we discussed the the lowest level elements of Java: values, variables, and expressions. And in the Chapter 1 Introduction we wrote bits of code inside a
main
method without looking too deeply into how that works.
In this chapter we’re going to look more closely at methods, which are Java’s way of creating procedural abstractions. Methods are named chunks of code that we can call in order to run the code. In other languages they are called lots of things such as functions, procedures, or subroutines. And in block programming languages like Snap! they are called blocks.
But whatever they are called, procedural abstractions, like all abstractions, hide certain details. Like variables abstract away the details of particular values by letting us refer to a value with a meaningful name, methods abstract away the details of how a computation is performed by letting us refer to the computation with the name of the method.
Writing methods lets us break a large program into problem down into smaller, more manageable chunks. Additionally, we can also use methods written by other programmers without having to worry about the details of exactly how they work. We just need to know the method’s name and what arguments it expects. Later in this unit we’ll look at several methods from the class
Math
that comes with Java, which save us from having to know, for instance, how to compute square roots.