Welcome to Lesson 14!

Learning Objectives

By the end of today's class, you should know...
  • How do you write a simple method?
  • How do you write a method call?
  • What is the order of the statements that are executed when a method call is made?
  • What is the difference between a local and global variable?

1. Lesson 13 Practice Exam Questions

  • What is the advantage of using a do-while loop instead of a while loop?
A do-while loop guarantees that...

  • There is a problem in the below code. Write one line of code to fix it:

System.out.print("Please enter your 9 digit password: ");

int password = input.nextInt();

System.out.print("Enter your user name: ");

String userName = input.nextLine();

System.out.println("You entered: " + userName + ", " + password);

  • Fill in the two missing lines of code to handle InputMismatchException:

        int age;
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter your age: ");

    while(                            ) {

        System.out.println("Please enter numbers not text!");   

        System.out.print("Please enter your age: ");
    }     age = input.nextInt();

2. Introducing Methods

Java comes with predefined methods

  • Math.pow(base, exponent)
  • Math.sqrt(number)
  • length()
  • substring(start_index, end_index)
  • charAt(index);
  • nextLine(), nextInt(), hasNextDouble(), etc.
  • Any others?
  • What do they all have in common? Notice any similarities in their syntax?

Method Vocabulary

  • Example:  sqrt method returns, or computes, the square root of a number
double the_root = Math.sqrt(9.0);
  • The number, 9.0, is called the argument
  • the_root will contain 3.0

Method Calls

  • sqrt(9.0) is a "method call."
  • It invokes, or sets in action, the sqrt method
  • The argument (9), can also be a variable or an expression
  • A method call can be used like any expression:
double bonus =  Math.sqrt(sales) / 10;

System.out.println("The side of a square with area " + area
         + “ is “
         + Math.sqrt(area));

Method Call Syntax

  • Method_name (Argument_List)
  • Argument_List is a comma separated list:  (Argument_1, Argument_2, … , Argument_Last)   

side = Math.sqrt(area);
System.out.println("2.5 to the power 3.0 is "
         + Math.pow(2.5, 3.0));

3. Writing Our Own Methods

Grouping Repeated Commands

  • Some of the main() methods in our programs have been getting lengthy and complicated (See above activity with Strings!)
  • The biggest problem in developing software is managing the complexity of programs
  • We can improve our code by organizing it into smaller pieces known as methods
  • Methods are a key tool in creating easy-to-understand programs that can be changed easily

Video: Chris Bosh Explains Functions (methods)

What is a Method?

  • As developers, we need to know how to write and call methods

    Method = a named block of statements that can receive input, perform an action, and optionally return a value

  • Methods are like little programs in our larger program
  • We give each little method commands we want executed
  • We call the method whenever we want the commands executed
  • When the method has finished running, program execution returns to the point just after the code that called the method

Example Application for a Method

  • As an example, recall our test code to validate user input:
public static void main(String[] args) {
    double number = 0.0; // initialize value
    Scanner input = new Scanner(System.in);    

    while (number <= 0) { System.out.print("Enter a positive number: "); number = input.nextDouble(); if (number <= 0.0) { System.out.println("You must enter a positive number\n"); } } System.out.println("\nYou entered: " + number); }

Method Syntax

  • The general syntax for defining a method is:
    public static returnType methodName(parameter1, ..., parametern) {
  • Where:
    • returnType: the data type of the value returned
    • methodName: the name you make up for the method
    • parameterx: the input values, if any
    • statements: the list of statements to execute when the method is called

Example Program with a Method

  • As an example, the following program has a simple method to add two numbers
  • Notice that the code has two methods: add() and main()
  • The second method add() can be placed anywhere outside of main().
public class MethodTest {
public static int add(int num1, int num2) {
int sum = num1 + num2;
return sum;

public static void main(String[] args) {
int result;
System.out.print("The sum of 2 and 5 is: ");
result = add(2,5); //first "call" to the add method

System.out.print("The sum or 7 and 9 is: ");
result = add(7,9); //second "call" to the add method

Method Name

  • Every method must have a name that identifies the method
  • Method names follow the same rules as variable names
  • Technically, we can use any valid identifier for a method name
  • However, we should use a name that suggests the action the method performs
  • In our example, add suggests that the method will return the sum of two numbers

Method Structure

  • The first line of a method is known as the method signature
    public static int add(int a, int b)
  • The curly braces {...} contain the method body
  • The method body is the list of statement the method executes when called
  • The method signature describes the name, inputs and output of a method
  • We will look at these features in more detail in the following sections


  • When defining a method, it is worth thinking about what helpful action it will perform
  • We can make the method more useful if we give it parameters
  • The parameters for an add method would be the two numbers to sum
  • Read through the following code to identify how the code makes use of the parameters

Example Code with Method Parameters

public class MethodTest {

    public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter two numbers to add: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
        int result = add(num1, num2);
System.out.print("The sum of " +num1
            + " and " + num2 + " is: " + result);

    public static int add(int num1, int num2) {
int sum = num1 + num2;
return sum;

Parameter List

  • We must have parenthesis after a method name
  • Inside the parenthesis, we define a list of zero or more parameters
  • Parameters are the inputs to a method
  • In our example, we have two parameters inside the parenthesis
    public static int add(int a, int b)
  • Parameters are the declaration of a new variable, even though they are declared inside parenthesis
  • Each parameter must have both a type and a name, just like a regular variable
  • If we have more than one parameter, we separate them with commas
  • Any parameter that we declare must be given an argument when we call the method
  • In the following image, the value of arguments num1 and num2 are copied to the parameters a and b

Passing Arguments to Method Parameters

Arguments and Parameters

  • Depending on our background, we might use the term arguments or parameters for the values passed to methods
  • The terminology is not that important
  • However, the way I will use the terms is:
    • A method definition has parameters
      public static int add(int a, int b) { // a and b are parameters
          // ...
    • A method call passes arguments
      add(num1, num2); // num1 and num2 are arguments
  • Arguments are values we pass into methods
  • When the argument drops into a method, it lands in a parameter
  • A parameter is just like other variables in the method
    • Except that a parameter gets initialized by an argument
  • The important part is:

    We must pass every method parameter an argument.

  • The arguments must be in the same order as the parameters
  • Also, the argument value must be compatible with the type of the parameter
  • For example, we cannot call add() with: add("Jennifer", "Parrish");

Returning a Value

  • The first word after public static in the method signature is the return type
    public static int add(int a, int b)
  • The return type specifies the type of data the method outputs
  • In our example the return type is an int

Return Statement

  • Methods that return a value must execute a return statement
    return result;
  • For instance, our example method add() has a return statement
    public static int add(int a, int b) {
        int sum = a + b;
        return sum;
  • Note that the type of the returned valued must be compatible with the method return type
  • The returned value is substituted for the method call in the calling code
    sum =>[replaces]=> add(num1, num2)
  • We must save the returned value if we want to process it later in the program
    int total = add(num1, num2);

Returning a Value from a Method

Returning an Expression

  • The value after the word return can be an expression
  • It does not have to be just the name of a variable
  • We could rewrite our return statement to the following:
    return a + b;

Multiple return Statements

  • We can have more than one return statement in a method
  • The first return statement reached is the one executed
  • We might have multiple returns if we have if-statements with alternate actions, like:
    if (x > 400) {
        return 1;
    } else {
        return 0;
  • We do not have alternate actions in our simple add method and so have only one return statement

Activity 14.1: Writing a Method (10 pts)

In this exercise we define our own method.

  1. Open a new Java project called Activity14 with a class named Sub
  2. Copy the following program method above or below your main method compile and run the starter program to make sure you copied it correctly.
    public static int add(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
  3. Alter the signature for a method named sub that receives two int numbers and returns an int value, like we did for the add() method
    returnType sub(two_int_parameters)
  4. Inside the method body, subtract the second parameter from the first and return the value, like we did for the add() method.
        int sum = num1 + num2; // from add() method, CHANGE THIS!
        return sum;
  5. Compile and run your code. 
  6. Inside the main() method, enter these statements:
        System.out.print("Enter two numbers to subtract: ");
        int num1 = input.nextInt();
        int num2 = input.nextInt();
        int diff = sub(num1, num2);
        System.out.println("Difference=" + diff);

    The fourth line contains the method call.

  7. Compile and run your modified program and verify the output looks like:
    Enter two numbers to subtract: 3 1
  8. Save your file and submit it to Canvas.

Completed Program

When finished, your application should look like the following:

complete program code

4. Variable Scope and Parameters

Variable and Parameter Scope

  • A variable declared inside a method can only be used within that method

    Local variable: a variable that can only be accessed within a method or block.

  • Parameters are a local variable and thus can only be used inside the method in which they are declared as well
  • As an example of a local variable, we declared sum inside the add() method:
    int sum = a + b;
  • In addition, we declared another variable named total inside main():
    int total = add(num1, num2);
  • These variables cannot be accessed outside the method they were declared within


  • The area of code that a variable can operate within is known as it's scope

    Scope: the enclosing area within which a variable exists

  • Because of scope, we can use variables with the same name in different methods
  • To send information to a methods we must include a parameters:
    public static int add(int a, int b)
  • When the method call is made, we send the arguments to the parameters:
    add(num1, num2)
  • The values of num1 and num2 are copied to the parameter variables a and b

Example of Scope - Below num1 and sum are out of scope.

5. Flow of Control for a Method Call
  • To use methods well, we must understand their flow of control
  • In our example, the program starts executing in the main() method
  • When our program gets to the following statement, it stops executing in main() and jumps to our method: int total = add(num1, num2);
  • The program executes the statements in the method and then returns to the statement from which it jumped
  • When the method returns, the returned value replaces the method call
  • After returning, the program completes processing the calling statement and then moves on to the next statement
  • In our example, the statement saves the returned value in the variable: total
  • Every time the flow of control reaches a method call, the program:
  • Temporarily stops executing in the current method
  • Jumps to the called method and executes the statements of that method
  • Returns to the point in the code from which it jumped

Method Call Flow

  1. Every program starts executing at the start of main().
  2. When reaching a method call, arguments are copied to the parameters.
  3. Method code executes until reaching a return statement.
  4. Return statement returns a value to the method call.
  5. Calling method continues after the method returns.

Activity 14.2: Tracing a Method Call (10 pts)
  • List the line numbers of each statement of your program from Sub.java in the order the lines are executed.
  • For example, if main() starts on line 9, statements are executed as follows: 9, 10, 11, 12, ...
  • Note: Do not bother to list blank lines or lines containing only a curly brace {}.
  • Submit your list of line numbers in the text box on Canvas for this activity.

Activity 14.3: Being Methodical (10 pts)

  • Inside your Activity14 folder, create a new Java class called Methodic
  • Copy and paste the below starter code into your file:
* @author
* CIS 36A
* Activity 14.3
public class Methodic {
public static void main(String[] args)
System.out.println("***Testing areaRectangle***\n");
System.out.printf("Should print 15.0: %.1f\n", areaRectangle(5.0, 3.0));
System.out.printf("Should print 5.3: %.1f\n", areaRectangle(3.5, 1.5));

System.out.println("***Testing areaTriangle***\n");
System.out.printf("Should print 7.5: %.1f\n", areaTriangle(5.0, 3.0));
System.out.printf("Should print 2.6: %.1f\n", areaTriangle(3.5, 1.5));

System.out.println("***Testing minNum***\n");
System.out.println("Should print 2: " + minNum(9, 2));
System.out.println("Should print 9: " + minNum(9, 9));
System.out.println("Should print 2: " + minNum(2, 9));

System.out.println("***Testing firstLetter***\n");
System.out.println("Should print A: " + firstLetter("Abracadabra"));
System.out.println("Should print z: " + firstLetter("zebra"));
System.out.println("Should print h: " + firstLetter("hello there!"));

System.out.println("***End of Tests***");


  • Then, either above or below main (not in the {} for main), but inside the { } of the class Methodic, write the following methods:
  • Name: areaRectangle
    • Takes 2 double parameters - one for the length and one for the width
    • returns the area of the rectangle as a double
  • Name: areaTriangle
    • Takes 2 double parameters - one for the base one for the height
    • returns the area of the triangle as a double
  • Name: minNum
    • Takes 2 integer parameters
    • returns the smaller of the two numbers as an integer
  • Name: firstLetter
    • Takes 1 String parameter
    • returns the first character in the String
  • After writing your methods, compile and run your code.
  • Adjust any methods that do not give the correct output in the tests
  • When all of your tests pass, submit your program to Canvas.

Wrap Up

Label the components of the following method:

public static double calc_area_circle(int radius) {

    double area = 3.14 * radius * radius;

    return area;


Method Name:

Return type:


Write the following method:

  • Name: sumSquare
    • It takes two integer parameters
    • squares each number (multiplies the number by itself) and then sums the squared numbers
    • returns the sum as an integer

Given the starter code below, call the sum of squares method:

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1, number2, sumSquares;

System.out.print("Enter the first number: ");
number1 = input.nextInt();

System.out.print("Enter the second number: ");
number2 = input.nextInt();

//call the method here!

System.out.print("The sum of squares is: " + sumSquares);

Upcoming Assignments
  • Activities 14.1-14.3 due Thursday at 11:59pm
  • Assignment 13 due Friday at 11:59pm
  • Quiz 7 due Friday at 11:59pm
  • Assignment 14 due next Tuesday at 11:59pm

~Have a Great Weekend!~