Welcome to Lesson 16!

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?


  • Practice Midterm 2
  • Practice Midterm Answer Key
  • Midterm 2 next class
    • Similar in format to midterm 1
    • ~12 short answer/multiple choice questions
    • 1 complete program
    • Covers material from Lesson 9 - today's lesson (1 simple method on the midterm)
  • Don't forget Lab 8 and Quiz 7 due Friday
  • Assignment 16 posted - due Tuesday after Thanksgiving
    • Challenging assignment! Don't wait until the night before to complete it!
  • Last day to drop with a 'W' is tomorrow
    • Please check your current grade on Canvas
    • Better to drop with a 'W' than to get an 'F' in most cases
    • Please feel free to talk to me

Review Activity

With a partner, answer the following questions:

  • What is the problem with the code below? Alter it by adding a single line:
System.out.print("Enter your age: ");

int age = input.nextInt();

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

String name = input.nextLine();

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

  • Change the following while loop into a do-while loop:

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

String password = input.next();

while (password.length() != 9) {

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

    password = input.next();


  • Add in the missing lines of code to the program below to handle the case where a user enters a String when you are expecting an integer input:

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

    while(                            ) { //fill in the missing test condition here

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

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

Introducing Methods

Java comes with predefined methods

  • 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));

What methods have we seen so far in this class?

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

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));

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); }
  • What if we need to enter two validated numbers into a program?
  • We want to process the first number after input and then input the second number
  • Doing so, we would end up with code like this:

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);

    while (number <= 0) { System.out.print("Enter a second 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);

  • Our program would be easier to write if we could get the second input without repeating the code
  • With methods, we give the list of commands a name and then run the list by calling the name
  • Using methods we keep all the code in one place and avoid duplication
  • Avoiding duplication reduces the complexity of our code and makes it easier to understand and change

Programming Style: Avoid Duplicating Code

  • Duplicate code can lead to problems such as:
    • Long repeated sections that are more difficult to understand than shorter sequences
    • Repetition of largely identical code within which it is difficult to see the different purposes of each section
    • Update problems where we make changes in some sections but overlook making changes in other sections
  • If we find ourselves writing similar code of three or more lines multiple times, we should consider writing a method

Defining a Method

  • In this section we look at method definition syntax and examine a simple example method
  • After we understand the syntax we can write more complicated methods

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 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 static int add(int num1, int num2) {
int sum = num1 + num2;
return sum;

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();
System.out.print("The sum of " +num1 + " and " + num2 + " is: ");
int result = add(num1, num2);

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 16.1: Writing a Method (10 pts)

In this exercise we define our own method.


  1. Open a new Java project called Sub with a class called Sub.java
  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:

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.

Activity 16.2: More Method Practice (10 pts)

  • Open Eclipse and create a new project called Methodic with a Java class called Methodic.java
  • Copy and paste the below starter code into your file:
 * @author
 * CIS 36A

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 in 2 double parameters - one for the length and one for the width
    • returns the area of the rectangle as a double
  • Name: areaTriangle
    • Takes in 2 double parameters - one for the base one for the height
    • returns the area of the triangle as a double
  • Name: minNum
    • takes in two integer parameters
    • returns the smaller of the two numbers as an integer
  • Name: firstLetter
    • takes in one 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
  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments
  • Assignment 16 due Tuesday after Thanksgiving
  • Lab 8 due Friday
  • Quiz 7 due Friday
~Have a Great Weekend!~