Lesson 3 - Methods
Here's a short lesson on one of the building blocks of Java that will prepare you for object-orientated programming: methods.
Method signature
A method (also known as a function in other languages) is essentially a function, very similar to one that you would encounter in math class. It has an input, an output, and a name (or identifier), though these must have specific data types (think a limited domain/range). Here is a sample method (isEven
) being declared within a class:
public class Example { public boolean isEven(int num) { if (num % 2 == 0) { return true; } return false; } public static void main(String[] args) { //main method //code executed here first } }
In this example, the method signature is simply public boolean isEven(int num)
. It consists of visibility modifiers (public
, private
, protected
, etc.), a return type (boolean
), a method identifier (isEven
), and a set of parameters (int num
). These parameters must each have a datatype, followed by an identifier, similar to declaring a variable.
To list multiple parameters, list each one individually within the parentheses, then separate them with a comma, like in the following example:
public int getNumRpPowerUp(int redScore, int blueScore, boolean autoQuestComplete, int numClimbs, boolean levitateUsed) { int totalRp = 0; if (redScore > blueScore) totalRp+=2; if (redScore == blueScore) totalRp++; if (autoQuestComplete) totalRp++ if (numClimbs == 3 || numClimbs == 2 && levitateUsed) totalRp++ return totalRp; }
Note that a value with the same type as the specified return type (int
in this case) must be returned by the method. This is accomplished by typing the word return
followed by a variable or literal value of the specified return type. For instance, the statement return 0;
would be valid in getNumRpPowerUp
as well. Note that the method immediately ends once a return statement is executed.
It it possible for a method to have no parameters and/or return type as well. With no parameters, simply leave the contents of the parentheses following the method name blank:
public String getInfoString() { return "Hello World!"; }
If you don't want to return a value from the method, the return type should be specified as void
. A return statement is not necessary:
public void printInfo(int currentMatchNum, String scoutName) { System.out.println(scoutName + " - Match " + currentMatchNum ); }
You've already used methods to find properties of an object or to compute values, such as with str.length()
or Math.pow(base, power)
. In general, a method call is accomplished by typing the method name, followed by its parameters. The return value (if there is one) can then be used, either within a conditional statement, loop, or assigned to a variable:
int red = 200, blue = 30, climbs = 1; boolean levitated = true; int rpGained = getNumRpPowerUp(red, blue, true, climbs, levitated); while (isEven(rpGained)) { //do something }
Why methods?
So, why are methods so important if they're just executing a block of pre-written code? Well, creating multiple methods in an application or program allows you to break down a problem and do certain tasks repeatedly. For instance, if you wanted to test if a series of numbers were even in different parts of a program, it would be easier to make a call to isEven(num)
rather than remembering that if a number mod 2 is 0, it is even. Another way to structure an application is to have methods responsible for specific tasks, such as saving a file or verifying if a password matches the one that was stored.
As long as you test a method after you write it and ensure it gives the correct output for a variety of input parameters, you can use it throughout an application without needing to refer back to the actual method's source code. That also makes it easy to collaborate with each other, as each person working on a project could be responsible for writing and testing one method; as long as those work independently, you could implement them together in the final product.
Overloading methods
Sometimes, a method should be able to have different set of parameters, of different data types. In this case, the parameter list will need to be modfied:
public double average(int num1, int num2) { return (num1+num2)/2.0; } public double average(double a, double b) { return (a+b)/2.0; }
Depending on the datatypes of the parameters when you make the method call, the compiler will know which method to execute. Note that the return type for a particular method name must always be the same, and a method cannot be overloaded if its signature is otherwise identical (parameters have the same datatypes, in the same order).
Recursion
Like in math, methods can call themselves or other methods within the body of their code. For instance, the following returns the n
th Fibonacci number (1, 1, 2, 3, 5, ...):
int fib(int n) { if (n==1) return 1; if (n==2) return 1; return fib(n-1)+fib(n-2); }
Recursion is useful for creating simple methods, but their running time can sometimes be slow, and you must always ensure that you reach a base case (n==1
or n==2
in this example) that returns a literal value. Refer to the binary search method if you want to see a more complex example of recursion.
Algorithmic challenges
Do as many as you want, until you get a good feel of when to implement methods and how to break down a problem:
-
Write a recursive method to compute the factorial of a number. Note that 0! is equal to 1.
-
Write a program that takes any English sentence without punctuation as an input, then converts it to Pig Latin.
-
Implement a more efficient (non-recursive) algorithm to find the n^\text{th} Fibonacci number
-
Determine the sum of all prime numbers from 2 to a number specified by the user.
-
A number is superb if and only if the sum of all of its factors (excluding itself) is less than a number. Write a program to determine the number of superb numbers between two numbers (e.g. 1 and 100) that are specified by the user.
-
Given a series of variable identifiers in camelCase, identify the number of actual words in the string (e.g. numberOfRankingPoints has four actual words).
-
Given the length of a set of integers S, followed the elements (numbers) of S, determine if S contains only consecutive integers, without repeats (e.g. {3, 5, 4, 6} does, while {6, 4, 3} and {1, 2, 2, 3} do not).
-
Given a series of lowercase strings without spaces or punctuation, determine if any two adjacent strings (inputted right after each other) are anagrams of each other.
-
Write a program to determine if a number is a palindrome.
-
Write methods that compute the least common multiple and greatest common factor of two positive integers.
Please email or DM me via Slack any challenges that you finish for feedback!