Methods were designed to:
Increase the readability of the program
Increase the ability to debug a program
Reduce the redundancy of code
Incorporate the concept of Separation of Duties/Divide and conquer
Examples of these methods are:
println()
nextLine()
nextInt()
charAt()
length()
split()
toUpperCase()
hasNext()
In reality, methods support the idea of the divide-and-conquer technique, which consists of breaking the problem into sub-problems and solving them independently to solve a larger problem.
There are two concepts that you need to understand for methods
Method definition
Method call (invocation)
Once the methods are defined, the code of your traditional classes will change:
When you define, a class method MUST be inside the class's scope but outside of the primary method.
Before Methods:
public class Whatever{
public static void main(String [] args){
//... all your code is in the main
//...
}
}
Methods use the divide and conquer technique. The divide and conquer technique means that the problem is broken into "small pieces" and each piece performs specific operations/tasks. For example, an example of a divide and conquer strategy is to break the main method into different methods and then call each method to perform specifics. Consider the code Whatever.java from the previous section now a skeleton of the class might look like this:
public class Whatever{
public static void main(String [] args){
// method calls belong here
}
m1()
{
// ...
}
m2()
{
// ...
}
// …
}
Here is a list of methods that you have been using for the past 8 weeks.
next()
nextLine()
nextInt()
nextDouble()
println(a String)
pow(an int, an int)
sqrt(int)
toUpperCase()
toLowerCase()
compareTo(String)
equals(String)
equalsIgnoreCase(String)
charAt(int)
length()
showMessageDialog(null, String)
1. In order to make it work, you need the "." at the beginning of each method
2. Parenthesis/arguments. All of them have parenthesis. However, there are two types.
a. (): they are called empty arguments. This means that there are no arguments for this method
b. (data type): inside the parenthesis, you can provide arguments. You need to specify each argument data type.
3. Camel case style. The name of the methods follows the format of the camel case.
Depending on your program's context, you can call the methods that you define in the previous section. Usually, the methods are called from the main.
1. Call the method with an actual value. Do not provide the data type in the parameters
public static void main(String [] args){
f(2);
}
2. Anticipate the data type you will receive from the method call. You can find out the data type by checking the return type of the method definition
public class MethodExample01{
public static void main(String [] args){
int solution = f(2);
}
public static int f(int x){
// .. code omitted
}
}
3. Report intermediate steps from the main. In this particular example, notice that the variable solution in the main now contains the result obtained by calling the method.
public class MethodExample01{
public static void main(String [] args){
int solution = f(2);
System.out.println("The solution is: "+solution);
}
Whatever happens under the scope of the method lives and stays there. Once the method returns the value that is specified in the method header, that operation expires.
For example, in our case, notice that we call the variable in the main that will hold the value solution AFTER the method f is called with the value 2. In the method f, the variable result holds the quick calculation of the function f. Once it hits the return, all the variables (including the result) disappear.
Method definition is composed of the following formula (see method Header see: page 272) is composed by:
<encapsulation type><modifiers><return type><id>(<parameter data type><id>, ...)
where the following items:
encapsulation type: this is the visibility of the method according to the scope of the class or the package.
public
private
protected
package (will not be used in methods only in classes in CS II)
modifiers: allows you to perform operations inside/outside the class. It allows you to overwrite methods and overload
static
final
abstract
interface
return type: what this method "gives back" once you called the method.
Eight primitive types (int, short, long, float, double, char, boolean, byte)
Object, e.g., String
void
Id: the name of the method
An identifier that makes the method meaningful (camel case style)
For parameters (if available): these are the values that are inside the parenthesis
Data type: i.e., eight primitive types, any object (e.g., String)
Id: the name of the parameter
E.g., Consider the functions from pre-calculus that you needed to solve back in middle school
f(x) = x2 + 3
f(2) = (2)^2 + 3
= 4 + 3
= 7
f(x) = x2 + 3
If I called the function with f(2), I would get: 7
Name of function: f
Parameter: x
The data type of the parameter: int
What will the function return once evaluated: an int
By using the previous components mentioned above, we obtain:
public static int f(int x) // method header
By elaborating the body of the method: Notice that we state that our returning data type is an int; it is recommended to create a place holder for that and return it immediately as follows:
public static int f(int x){
int result = 0;
return result;
}
This way, your code can compile without any problem. Not the remaining piece of code is the actual calculation of the function (i.e., x2 + 3). We can simply make the statement in Java as "x * x + 3", resulting in the following method:
public static int f(int x){
int result = 0;
result = x * x + 3;
return result;
}
public static void main(String [] args){
for(double x = 1; x <= 20; x+=0.1){
double y = f(x);
System.out.println("f("+x+"): \t"+y);
}
}
We can provide flexibility to the computer user to choose whatever option he/she wants to use. The method f takes an int as a parameter, but what about if we would like to provide a double? We can have another method with the same name but with a different header. The header is the part of the method that will provide the parameter data type. For example:
public static double f(double x){
double result = 0;
result = Math.pow(x,2) + 3;
return result;
}
Noticed in this version, we exercise the invocation of the Math.pow() method. This is an example of how to invoke methods inside of another method.
How can we define a method in Java?
To guarantee a successful compilation and successful execution of your program, we recommend doing the following steps. We are going to keep using the function f(x) as an example:
Identify all the elements of the
Move outside the scope of the main, but stay inside the scope of the program
public class MethodExample01{
public static void main(String [] args){
}
public static int f(int x){
}
}
3. In order to compile your program successfully. You must return the data type that you claim you will use in the method header
public static int f(int x){
int result = 0;
return result;
}
4. For the rest, use the variable that you declared internally to perform operations; in this case, will perform the actual operation of f(x)
result = x * x + 3;
5. Combine Step 3 and Step 4 in the method:
public static int f(int x){
int result = 0;
result = x * x + 3;
return result;
}