Welcome to Lesson 17!


Learning Objectives

By the end of today's class, you should know...
  • What is the difference between a global and local variable?
  • How do you trace a method call?
  • What are some style requirements for methods?
  • More method practice

Announcements

  • Midterm 2 next class! (Lessons 9 -16)
  • Assignment 17 due one week from today!
  • Return Quiz 6
    • If you got 3 or below, please get a free tutoring session on loops before the midterm on Thursday
  • Women in Computer Science Club meeting tomorrow!
    • 1:00-2:00pm in ATC 202
    • Samantha from San Jose Public Library
    • Teach basic coding skills to elementary and middle school students using curriculum from Google CS First


Review Activity


With a partner, answer the following questions:

  • 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:

Parameter(s):


  • Write a correct function call for the above method, passing it the value of 9, and storing the result in the cArea variable:

         double cArea = ???????????????????;

    System.out.println("The area of the circle with radius 9 is: " + cArea);


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

Scope

  • 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.



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:
    1. Temporarily stops executing in the current method
    2. Jumps to the called method and executes the statements of that method
    3. 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 17.1: Tracing a Method Call (10 pts)

  1. List the line numbers of each statement of your program from Activity 16.1 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 (}).

  2. Submit your list of line numbers in the text box on Canvas for this activity.

Some Style Requirements for Methods

  • Consider again our example method

public static int add(int a, int b) {
    int sum = a + b;
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();

int total = add(num1, num2);
System.out.println("Sum=" + total);
}
  • Note the placement of the curly braces
  • There are two common styles of curly brace placement for methods:
    1. Place the opening brace on the same line as the method heading:
      public static int myMethod() {
          // statements of the method
      }
      
    2. Place the opening brace under and lined up with the first letter of the return type:
      public static int myMethod()
      {
          // statements of the method
      }
      
  • We can use either style as long as we are consistent
  • Also notice the indentation of the statements inside the method
  • As before, we always indent 3-4 more spaces after an opening curly brace
  • After the closing curly brace, we no longer indent the extra 3-4 spaces
  • Indenting makes it easier to see the block of code
  • In addition, method names always start with a lower case letter like variables
  • We can tell the difference between method and variable name because methods have parenthesis


Activity 17.2: Calculating Your Salary (10 pts)

  • Open up Eclipse and create a new Java project called Salary.
  • Copy and paste the starter code below into the file.
  • NOTE: Do not change the starter code! All you need to do is add to it.
import java.util.Scanner;

public class Salary {

    //Write your methods here
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int hours;
        double hourly_wage;
        double weekly_salary = 0;
        double monthly_salary = 0;
        double yearly_salary = 0;
        System.out.println("This program will calculate your weekly, monthly "
                + "and yearly salary!");
        System.out.print("Please enter your hourly wage: ");
        hourly_wage = input.nextDouble();
        System.out.print("Please enter the number of hours you work each week: ");
        hours = input.nextInt();

        //call methods below
        weekly_salary = //method call goes here
        monthly_salary = //method call goes here
        yearly_salary = //method call goes here
              
        System.out.printf("You make $%.2f per week\n", weekly_salary);
        System.out.printf("You make $%.2f per month\n", monthly_salary);
        System.out.printf("You make $%.2f per year\n", yearly_salary);
        input.close();
    }

}

  • Now write three methods as follows and place them above main:
    • weeklySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the weekly salary
    • monthlySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the monthly salary
    • yearlySalary()
Takes in an integer argument for the number of hours worked each week
Takes in a double argument for the hourly wage
Returns a double for the yearly salary
Assume that you work 50 weeks a year (2 weeks vacation)
  • Add a method call and store the result as the appropriate variable.
weekly_salary = //method call goes here
monthly_salary = //method call goes here
yearly_salary = //method call goes here
  • Now, run your code and verify that it prints the correct values for each salary type.
  • When you are finished, upload your file to Canvas.
  • Your output should look identical to the following (except user input will vary):


Group Activity: Tracing a Method Call

What is output by the following program? (Do not run the code -- work it out by hand)


public static int mystery(int param) {
System.out.println("param=" + param);
param = param * 2;
return param;
}

public static void main(String[] args) {
    int num = 2;
System.out.println("At first, num=" + num);
int result = mystery(num);
System.out.println("After calling, num=" + num);
System.out.println("And result=" + result);
}
  1. At first, num=2
    param=2
    After calling, num=4
    And result=4
    
  2. At first, num=2
    param=4
    After calling, num=4
    And result=4
    
  3. At first, num=2
    param=2
    After calling, num=2
    And result=4
    
  4. None of these


Activity 17.3: 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();
     
        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();
         
        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();
       
        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();
     
        System.out.println("***End of Tests***");
     
    }
  
}

  • Then, either above or below 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.


Upcoming Assignments

~See You Thursday!~