Variables are the nouns of a program. Methods are the verbs. A method is a named block of code that runs whenever you call its name. This page starts with notes on methods and the program from class. Then you use methods to finish a terminal program with two menus.
Method notes · The class program · One lab · Seven methods to write
Notes
Methods in Java
What is a method?
A method is a block of code with a name. Writing the method teaches the program how to do a job. Calling the method tells the program to do that job now. Methods are also called functions.
You write the code once and call it as many times as you like.
Each method does one job, which keeps main short and readable.
When a job needs fixing, there is one place to fix it.
You have been calling methods since the first lab. System.out.println(...), keyboard.nextInt(), and word.length() are methods that someone else wrote. main is a method too. It is the one Java runs first.
A first method
This program has two methods: main and helloWorld.
public class MethodsLecture
{
public static void main(String[] args)
{
helloWorld();
helloWorld();
helloWorld();
}
public static void helloWorld()
{
System.out.println("Hello world!!!");
}
}
Output
Hello world!!!
Hello world!!!
Hello world!!!
The method is written once and called three times. Each call runs the method’s code one time. Here is what happens at each call.
main reaches the line helloWorld();.
Java jumps to the helloWorld method and runs the lines between its braces.
At the method’s closing brace, Java returns to main and continues with the next line.
Where a method goes. Write each method inside the braces of the class and outside the braces of main. One method never goes inside another. The order of the methods in the file does not matter, because Java always starts at main.
Reading the first line of a method
The first line of a method is its header. Every word in it has a job.
public static void helloWorld()
Part
What it means
public
Any file in the project may use this method. The other choice, private, keeps a method for its own file.
static
The method belongs to the class itself, so main can call it by name right away. A method without static needs an object first. Objects come later in the course.
void
The return type. It names the type of value the method gives back. void means the method gives nothing back. It runs its code and stops.
helloWorld
The name you chose. You use it to call the method.
()
The parameters: the values the method needs in order to work. Empty parentheses mean it needs none.
For this class, begin every method with public static. The return type, the name, and the parameters are the parts you change to suit each method.
Parameters
A method that always prints the same message can do only one thing. A method that can greet any name is more useful. A parameter is a variable that receives a value when the method is called.
public static void betterHello(String name)
{
System.out.println("Hello " + name + "!!!");
}
Write a parameter the way you declare a variable: a type, then a name. Parameters can be of any type, including arrays: (String name), (int number), (int[] numArray).
The value you put between the parentheses of a call is handed to the parameter. There is more than one way to supply it.
betterHello("Bobby");
String name = "Pepito";
betterHello(name);
String differentName = "Sir Gunther the Penguin";
betterHello(differentName);
Output
Hello Bobby!!!
Hello Pepito!!!
Hello Sir Gunther the Penguin!!!
What the parameter holds during each call
The call
name inside betterHello
betterHello("Bobby");
"Bobby"
betterHello(name);
"Pepito"
betterHello(differentName);
"Sir Gunther the Penguin"
The names do not have to match. A variable in main and a parameter in a method are two separate variables. The call hands the value from one to the other.
More than one parameter
A method can take several parameters. Separate them with commas.
public static void printFruit(String fruit, int count)
{
System.out.println("I have " + count + " " + fruit + ".");
}
printFruit("mangoes", 3); // prints I have 3 mangoes.
Every call must supply a value for every parameter, in the same order and of the right type. These two calls do not compile.
printFruit("mangoes"); // the count is missing
printFruit(3, "mangoes"); // the values are in the wrong order
Giving a value back with return
Every method so far has been void. It does its work and gives nothing back. To get an answer out of a method, replace void with the type of the answer, and use return to send the answer back.
public static int square(int number)
{
return number * number;
}
When the call finishes, square(7) stands for the value 49. You can store that value, print it, or use it in a calculation.
int answer = square(7);
System.out.println("7 squared is " + answer); // prints 7 squared is 49
System.out.println(square(3) + square(4)); // prints 25
The return type tells you what comes back
Header
What the method gives back
public static void helloWorld()
Nothing
public static int square(int number)
A whole number
public static double average(int a, int b)
A decimal number
public static boolean isEven(int number)
true or false
Printing is not returning. A void method may print on the screen, but it hands nothing to the line that called it. A method with a return type must end by returning a value of that type. A return statement also ends the method at once.
Methods and arrays
Here is a method that does a larger job. It sorts an array of integers from least to greatest. A second method prints an array on one line.
public static void sortArray(int[] arr)
{
// Visit each position in the array.
for (int i = 0; i < arr.length; i++)
{
// Compare it with every number after it.
for (int j = i; j < arr.length; j++)
{
// If the number at i is bigger, swap the two.
if (arr[i] > arr[j])
{
// Placeholder so a value is not lost in the swap.
int placeholder = arr[j];
arr[j] = arr[i];
arr[i] = placeholder;
}
}
// The smallest remaining number is now at position i.
}
}
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
}
Each time the outer loop finishes one round, the smallest number that was left is in its final position. This table follows the array {5, 4, 3, 2, 1}.
The array after each round of the outer loop
Round finished
The array
Now in place
i = 0
1 5 4 3 2
The first number
i = 1
1 2 5 4 3
The first two
i = 2
1 2 3 5 4
The first three
i = 3
1 2 3 4 5
All five
Once the method exists, sorting any array of integers takes one line.
A method changes the real array. When you pass an int or a String, the method receives a copy of the value. When you pass an array, the method works on the same array that main has. That is why sortArray can be void. It gives nothing back, and arr1 is still sorted afterward.
When the program will not compile
These are the errors that appear most often while learning methods. The wording below comes from the Java compiler. Your editor may phrase it a little differently, but the key words are the same.
The message mentions
What happened
What to do
illegal start of expression
A method was written inside another method.
Move it below the closing brace of main, still inside the class.
non-static method … cannot be referenced from a static context
The header is missing static.
Begin the header with public static.
cannot be applied to given types
The call has too few or too many values.
Supply one value for each parameter.
incompatible types
A value in the call has the wrong type, or a void method was used as if it gave back a value.
Match each value to its parameter’s type. Check the return type.
missing return statement
The header promises a value, but the method does not return one.
End the method with return and a value of the right type.
cannot find symbol
The method uses a variable that was declared in a different method.
Pass the value in as a parameter.
not a statement
The call is missing its parentheses.
Write helloWorld(); with the parentheses, even when they are empty.
Quick reference
To do this
Write this
Write a method that needs nothing and gives nothing back
public static void helloWorld()
Write a method with one parameter
public static void betterHello(String name)
Write a method with two parameters
public static void printFruit(String fruit, int count)
Write a method that gives back an int
public static int square(int number)
Send a value back
return number * number;
Call a method
helloWorld();
Call a method and supply a value
betterHello("Bobby");
Call a method and keep its answer
int answer = square(7);
In class
The class program
This is the whole program from the notes in one file. To run it, save it in src as MethodsLecture.java. Change a call, add a call, or write a method of your own below the others and call it from main.
/*
* Method notes: the complete program from class.
*/
public class MethodsLecture
{
public static void main(String[] args)
{
// The method is called three times.
// Each call prints the message once.
helloWorld();
helloWorld();
helloWorld();
// Three ways to give betterHello its name.
betterHello("Bobby");
String name = "Pepito";
betterHello(name);
// The variable out here does not need the same name
// as the parameter inside the method.
String differentName = "Sir Gunther the Penguin";
betterHello(differentName);
// A method that gives a value back.
int answer = square(7);
System.out.println("7 squared is " + answer);
// Test the sorting method on three arrays.
int[] arr1 = {2, 5, 7, 1, 40, 0, 4};
int[] arr2 = {5, 4, 3, 2, 1};
int[] arr3 = {0, 1, -1, 2, -2, 3, -2};
sortArray(arr1);
sortArray(arr2);
sortArray(arr3);
outputArray(arr1); // 0 1 2 4 5 7 40
outputArray(arr2); // 1 2 3 4 5
outputArray(arr3); // -2 -2 -1 0 1 2 3
}
// No parameters, no return value.
public static void helloWorld()
{
System.out.println("Hello world!!!");
}
// One parameter: the name to greet.
public static void betterHello(String name)
{
System.out.println("Hello " + name + "!!!");
}
// One parameter, and an int comes back.
public static int square(int number)
{
return number * number;
}
// Sorts an int array from least to greatest.
public static void sortArray(int[] arr)
{
// Visit each position in the array.
for (int i = 0; i < arr.length; i++)
{
// Compare it with every number after it.
for (int j = i; j < arr.length; j++)
{
// If the number at i is bigger, swap the two.
if (arr[i] > arr[j])
{
// Placeholder so a value is not lost in the swap.
int placeholder = arr[j];
arr[j] = arr[i];
arr[i] = placeholder;
}
}
// The smallest remaining number is now at position i.
}
}
// Prints every value in an int array on one line.
public static void outputArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
This lab is one large problem. You are given a terminal program with two menus. The menus already work, but most of the choices do nothing yet. Your job is to write the methods that make every choice work.
What the starter already does
It prints the main menu, reads a number, and prints the menu again after each choice.
Choice 3 opens the math menu. In the math menu, choice 5 goes back to the main menu.
In both menus, a number that is not on the menu should print a response. The starter prints an empty line there. Replace it with a school-appropriate response of your own.
The one rule
Inside each if and else if branch, write one line: a call to a method. All of the work belongs inside your methods. The rule covers both menus.
else if (input == 2)
{
tellStory();
}
A branch holds no loops, no calculations, and no lists of print statements. Everything else is your choice: the names of your methods, the wording of your messages, your story, and your joke. Each method needs only to do its job.
Starter code
Save this in src as MethodLab.java. Fill in your name and date and run it once. Type 3, then 5, then 5, and compare with the example run below the code.
/*
* Name:
* Project: Method Lab
* Date:
*/
import java.util.Scanner;
import java.util.Random;
public class MethodLab
{
public static void main(String[] args)
{
boolean runTerminal = true;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome, user. What would you like to do?");
while (runTerminal)
{
System.out.println("1. Play rock paper scissors.");
System.out.println("2. Tell me a story.");
System.out.println("3. Math.");
System.out.println("4. Print out a full diamond.");
System.out.println("5. Exit out.");
int input = keyboard.nextInt();
if (input == 1)
{
// TODO: Call your rock paper scissors method.
}
else if (input == 2)
{
// TODO: Call your story method.
}
else if (input == 3)
{
mathUI(keyboard);
}
else if (input == 4)
{
// TODO: Call your diamond method.
}
else if (input == 5)
{
runTerminal = false;
}
else
{
System.out.println(""); // TODO: Write a school-appropriate response.
}
}
System.out.println("Until next time.");
keyboard.close();
}
public static void mathUI(Scanner keyboard)
{
boolean runMath = true;
System.out.println("Welcome, user. What math functions would you like to use?");
while (runMath)
{
System.out.println("1. Give me the factorial of a number.");
System.out.println("2. Find me the highest prime number below a given number.");
System.out.println("3. Tell me a math joke.");
System.out.println("4. Find me the volume of a sphere.");
System.out.println("5. Exit out.");
int input = keyboard.nextInt();
if (input == 1)
{
// TODO: Call your factorial method.
}
else if (input == 2)
{
// TODO: Call your highest prime method.
}
else if (input == 3)
{
// TODO: Call your math joke method.
}
else if (input == 4)
{
// TODO: Call your sphere volume method.
}
else if (input == 5)
{
runMath = false;
}
else
{
System.out.println(""); // TODO: Write a school-appropriate response.
}
}
}
// TODO: Write your methods here, below mathUI and above the last brace.
}
Example run of the starter
Welcome, user. What would you like to do?
1. Play rock paper scissors.
2. Tell me a story.
3. Math.
4. Print out a full diamond.
5. Exit out.
3
Welcome, user. What math functions would you like to use?
1. Give me the factorial of a number.
2. Find me the highest prime number below a given number.
3. Tell me a math joke.
4. Find me the volume of a sphere.
5. Exit out.
5
1. Play rock paper scissors.
2. Tell me a story.
3. Math.
4. Print out a full diamond.
5. Exit out.
5
Until next time.
The lines 3, 5, and 5 are what you type. Type whole numbers at the menus. The program expects a number there and stops with an error if it gets a word.
Brace style. Put each opening brace on its own line, and line up each closing brace with its opening brace. Indent the lines inside a block by four spaces. Write your methods the same way.
Read before you code
How the terminal works
The menu repeats until you exit
The variable runTerminal starts as true. The while loop prints the menu and reads a choice for as long as it stays true. Choice 5 sets it to false, so the loop ends and the program prints Until next time.
After any other choice, the loop goes around again and the menu comes back. You do not need to print the menu yourself. When your method finishes, Java returns to the loop.
mathUI is your model
The math menu is already a method, and the branch for choice 3 already follows the rule. It holds one line.
else if (input == 3)
{
mathUI(keyboard);
}
What happens when you type 3, then 5
Step
What Java does
You type 3
main calls mathUI(keyboard); and waits.
Inside mathUI
Its own loop prints the math menu and reads choices.
You type 5
runMath becomes false. The loop ends, and so does the method.
Back in main
Java continues after the call. The main loop goes around and prints the main menu.
Each of your methods fits into the program the same way. The branch calls it, it does its job, and Java returns to the menu.
Why keyboard is passed along
A method can use only its own variables: its parameters and the variables declared inside it. keyboard is declared inside main, so no other method can see it. That is why mathUI receives it as a parameter.
public static void mathUI(Scanner keyboard)
Any method of yours that reads what the user types needs the same parameter, and the call needs to supply it. A method that only prints, such as a story, needs no parameters.
One Scanner for the whole program. Pass keyboard to the methods that need it. Do not make a second Scanner inside a method, and do not close keyboard inside a method. The starter closes it once, at the end of main.
Main terminal · Choice 2
Your first method: tell me a story
void · No parameters · Write, call, run
Start with the story. It needs no input, so it is a good first method. The three steps here are the same three steps you will use for every method in the lab.
Step 1. Write the method.
Go to the TODO comment near the bottom of the file, below mathUI and above the last closing brace. Write a void method with no parameters. Give it a name that says what it does, and fill it with your own story.
public static void tellStory()
{
System.out.println("Once upon a time, ...");
// Add the rest of your story here.
}
Step 2. Call it from the menu.
In main, find the branch for choice 2. Replace the TODO comment with a call to your method.
else if (input == 2)
{
tellStory();
}
Step 3. Run and test.
Run the program and type 2. Your story should print, and then the main menu should appear again.
Check. Type 2 twice in a row. The story prints both times, with the menu after each. Then type 5 to exit.
Build one method at a time. Write it, call it, and run it before you start the next one. If something stops working, you know which method to look at.
Main terminal · Choices 1 and 4
Main terminal methods
These two methods are called from the menu in main.
Scanner parameter · Random · Comparing text
Choice 1. Play rock paper scissors
Ask the user to type rock, paper, or scissors. Let the computer choose one of the three at random. Print the computer’s choice and the result. One round each time the choice is made is enough.
Example run
Rock, paper, or scissors?
rock
The computer chose scissors.
You win!
Your wording may differ. Here is a plan.
The method reads input, so give it a Scanner parameter, as mathUI has.
Read the user’s word with keyboard.next().
Make a Random inside the method with Random random = new Random();. The import is already at the top of the starter.
random.nextInt(3) gives 0, 1, or 2. Turn that number into one of the three words and store the word in a String.
Compare the two words and print who won.
You have written this before. The comparison is Assignment 1, Problem 10. There both choices were typed into the code. Here one comes from the keyboard and one from Random. Compare text with .equals(). For a refresher on Random, see the Fundamentals Lab notes.
Check. To test every case, replace the random choice for a moment with a fixed word such as "rock". Try all three of your own choices against it, then change the fixed word. The table in Assignment 1, Problem 10 lists all nine results. Put the random choice back when you finish.
Nested loops · Spaces, then stars · A method that calls a method
Choice 4. Print out a full diamond
Print a diamond made of asterisks. The rows grow by two stars until the middle row, then shrink again. You decide the size. It may be fixed, or you may ask the user for it. A method that asks needs the Scanner parameter.
Example output for size 4
*
***
*****
*******
*****
***
*
Every row is some spaces followed by some stars. Count them for size 4 before you write any code.
Row
Spaces
Stars
1
3
1
2
2
3
3
1
5
4
0
7
5
1
5
6
2
3
7
3
1
In the top half, each new row has one fewer space and two more stars. The bottom half is the top half in reverse, without repeating the middle row. Write the top half first and run it. Then add the bottom half.
You have written this before. The staircase in Loops Lab, Problem 13 printed a row of stars whose length depended on the row number. The diamond adds a loop that prints spaces before the stars. The nested loop notes show where System.out.println(); belongs.
A method may call another method. You could write a small method that prints one row, with a header such as public static void printRow(int spaces, int stars). Your diamond method then becomes two loops that call it. The branch in main still holds one call.
Check. Size 1 is a single star. Size 2 has three rows of 1, 3, and 1 stars. Size 4 matches the example: seven rows, and the widest has seven stars with no spaces before it.
Math terminal · Choices 1–4
Math terminal methods
These four methods are called from the menu in mathUI. To test one, type 3 at the main menu first.
Scanner parameter · Running product · Return value
Choice 1. Give me the factorial of a number
Ask for a whole number from 0 through 12 and print its factorial. The factorial of a number is the product of every whole number from 1 up to it. It is written with an exclamation mark: 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition, 0! is 1.
Example run
Enter a whole number from 0 through 12:
5
5! = 120
Start a result at 1. Use a for loop that counts from 1 through the number, and multiply the result by the counter each time.
You have written this before. This is the running total from Loops Lab, Problem 5, with two changes. You multiply where you used to add, and the result starts at 1, because a product that starts at 0 stays 0.
Try a return value here. One way to build this is with two methods. The first takes a number and returns its factorial, with a header such as public static int factorial(int number). The second asks the user, calls the first, and prints the answer. The menu branch calls the second.
Why stop at 12? The largest value an int can hold is 2,147,483,647. 13! is larger than that, so the program would print a wrong answer.
Choice 2. Find me the highest prime number below a given number
Ask for a whole number and print the largest prime that is less than it. “Below” means less than. The answer for 29 is 23, even though 29 is prime. There is no prime below 2, so for an input of 2 or less, print a message that says so.
Example run
Enter a whole number:
100
The highest prime below 100 is 97.
Here is a plan.
Start a candidate at one less than the input.
Test whether the candidate is prime.
If it is not, subtract one and test again. Stop at the first prime you reach, or when the candidate drops below 2.
You have written this before. The prime test is Assignment 2, Activity 5. Give it a method of its own that returns true or false, with a header such as public static boolean isPrime(int number). Then the countdown can ask isPrime(candidate) each time around.
Check. Try these inputs.
Input
Highest prime below it
What it tests
10
7
Skipping 9 and 8
30
29
The first candidate is prime
29
23
The input itself does not count
3
2
The smallest prime
2
None
No prime to find
10000
9973
A long countdown
The last answer should look familiar. 9973 is the final prime from your Sieve in the Array Lab.
void · No parameters
Choice 3. Tell me a math joke
Print a math joke of your choice. This method is built the same way as your story: no parameters, no return value, and one call from the menu.
Check. Type 3 at the math menu. The joke prints, and the math menu appears again. You should still be in the math menu, not the main one.
Scanner parameter · Decimal input · Formula
Choice 4. Find me the volume of a sphere
Ask for the radius of a sphere and print its volume. The radius may be a decimal number. The formula is V = 4/3 × π × r³.
Example run
Enter the radius:
3
The volume is 113.09733552923255
Read the radius into a double with keyboard.nextDouble().
Java has π built in. Write Math.PI.
For r³, multiply the radius by itself three times: radius * radius * radius.
Write 4.0 / 3.0. When Java divides one int by another, it drops the decimal part, so 4 / 3 is 1. A radius of 3 would then give about 84.82, which is too small. You met this in Assignment 1, Problem 8.
Check. A radius of 0 gives 0.0. A radius of 1 gives about 4.18879. A radius of 3 gives about 113.09734. Your last few digits may differ slightly.
Before submitting
Fill in your name and date. Keep all of your methods in MethodLab.java.
Look at every if and else if branch in both menus. Each one holds a single method call.
Test every choice in both menus, and type a number that is not on the menu, such as 9. Each menu gives your own response.
After each method finishes, its menu appears again. Choice 5 in the math menu returns to the main menu, and choice 5 in the main menu ends the program.
Run the checks for the factorial, the highest prime, and the sphere.
Be ready to explain why keyboard is passed as a parameter, and how a void method differs from one that returns a value.