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?
  • What are the style requirements for methods?

Announcements

  • Midterm 2 one week from today
    • 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 function on the midterm)
  • Don't forget Lab 8 due Friday
  • Quiz 6 after the break
  • 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 a double:

          double gpa;
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter your gpa: ");
    while(                ) { //fill in the missing test condition here
       

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

        System.out.print("Please enter your gpa: ");
    }
    gpa = input.nextDouble();



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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14


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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24


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) {
        statements
    }
    
  • 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().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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.println(result);

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

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

Parameters

  • 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

    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);
System.out.println(result);
}

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.

Specifications

  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
    Difference=2
    
  8. Save your file and submit it to Canvas.

Completed Program

When finished, your application should look like the following:

Wrap Up
  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments
~Have a Great Weekend!~