Lesson: What are Methods?

Overview: 
Explore the concept of a Method, why they exist and why we need them.
Objectives: 

Understand the general concept of a Method and the use cases for Methods.

Content: 

Methods are reusable code blocks that are only executed when called from another location in your program. Methods are also called functions or subroutines. For our purposes, these names mean same thing. In other languages, the names may mean something a bit different.

In math, the parallel to a method is a function, like f(x). The function f takes in an input, x, and does something to it. Let’s say we want to square a number and then take three away from it. In math, we would write f(x) = x*x - 3. Then, we can later say f(2), and since we have defined what the function f(x) is, a reader would know that f(2) will give us 1 (4-3). This allows us to re-use a process that we may want to repeat throughout our code.

Methods help reduce complexity by taking code blocks that repeat and writing them in one place and then calling the blocks whenever we need them.

Methods streamline code by allowing us to break a complex algorithm into smaller sections of code, each easier to understand, but callable as part of the overall algorithm. That is, we can write a more complicated function by putting together smaller, simpler functions that each do a simpler step.

Methods allow objects to contain executable code (as well as data) which can be called by users of those objects. This is the basis of APIs in Java. We will ignore the object aspects of methods for the moment, looking only at method basics. For now, know that methods are defined inside Java classes and that a method cannot contain another method. In our example program Hello World, the block of code titled main is a method.

 

Navigation: