5: Iteration and Methods

What We Will Cover


Continuations

Homework Questions?

Questions from last class?

What is the value of x after the following code segment executes?

int x = 5;
if (x > 3) {
    x = x - 2;
} else {
    x = x + 2;
}

5.1: Iterating (Loops)

Objectives

At the end of the lesson the student will be able to:

  • Use while statements to repeat sections of code
  • Apply commonly-used looping patterns
  • Avoid common looping problems

5.1.1: Introduction to Loops

  • Loops are used to repeat sections of code
  • General loop structure:
    • Initialization code
    • Loop condition -- evaluated during the loop
    • Loop body
  • Java has 3 loop statements
  • while
    do-while
    for
    
  • However, you can use any loop statement and achieve the same result
  • Thus, I am only going to teach one loop statement at this time
  • Later on we will look at the other loop statements

5.1.2: Coding while Statements

  • The while loop is one of the simplest loop
  • Use a while loop to repeat a section of code
  • The repetition continues as long as the test condition remains true
  • while loop Syntax:
  • //Initialization
    ...
    while (condition) {  //loop exit condition
       //loop body
       ...
    }
    
  • Initialization statements usually precede the while loop
  • Checks condition at the start of every loop iteration
    • Continues as long as condition evaluates to true
  • Note that if the loop condition is initially false then the loop body never executes
  • The loop body can be a single statement or a block
  • You can put any legal statement in the body of the loop
    • Including if statements and other loop statements

Diagram of while Loop Operation

While flow chart

5.1.3: Example Application: Play Again Program

  • The following application simulates the play of an exciting game
  • Note the 3 important parts of the loop
    • Loop initialization
    • Loop condition
    • Loop body -- statements to execute repeatedly
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    import java.util.Scanner;
    
    public class PlayAgain {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
    
            String answer = "y";
            while (answer.charAt(0) == 'y') {
                System.out.print("Playing an exciting game!\n"
                    + "Do you want to play again? (y/n) ");
                answer = input.next();
            }
            System.out.println("Thanks for playing!");
        }
    }
    
    • Which statement initializes the loop variables?
    • Which part is the loop condition?
    • Which part is the loop body?
    • If line 5 was:
    • char answer = 'n';

      How many times would the loop execute?

    • Loops of this type are often called the main programming loop

    Formatting the Code

    • It is important to format the loop code correctly
    • Note how the repeated code is indented inside the loop
    • This lets us know visually what code is repeated and which is not
    • Also note the placement of curly braces
    • Different groups have different practices for placing curly braces in a loop statement
    • For the acceptable styles for this course see: Curly Braces

    5.1.4: Understanding the Main Loop

    • We can generalize the main loop of our example
    • Implementation can be different from one program to another
    • However, the basic structure is the same for most programs

    Program Flow with a Main Loop

    Main loop flow

    Notes on the Program Flow

    • Set Up (statements before the loop)
      • Declare and initialize variables
      • Provide instructions
    • Repeated steps (loop body)
      • Get User Input
      • Update Variables
      • Update Display
      • Program Done?
        • Check if the program is completed
        • Often the user decides to exit
        • Change variables in the test condition of the loop
    • Shut Down (statements after the loop)
      • Provide the user any final information
      • End the program

    5.1.5: Summary

    • Loops are used to repeat sections of code
    • General loop structure:
      • Initialization code
      • Loop condition -- evaluated during the loop
      • Loop body
    • The while loop is a simple repetition statement
    • Syntax:
    • //Initialization
      ...
      while (condition) {  //loop termination condition
         //loop body
         ...
      }
      
    • Most programs have a main loop
    • Statements inside the loop repeat until the program exits

    Check Yourself

    1. What are the three parts of any loop?
    2. How do you code a while statement?
    3. What is the purpose of a loop test condition?
    4. What is meant by the term main programming loop?

    Exercise 5.1

    Specifications

    1. Update the guessing game code shown below to let the user make as many guesses as they choose.
      1. Decide which statements need to repeat
      2. Write the while loop with a condition for exiting the loop
      3. Initialize the loop variables so the loop can run at least once
    2. Submit your program along with your other exercises for this lesson.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    import java.util.*;
    
    public class GuessingGame2 {
        public static void main(String[] args) {
            Scanner input  = new Scanner(System.in);
            int guess = 0;
    
            System.out.print("I'm thinking of a number "
                + " between 1 and 10.\nCan you guess it? ");
            guess = input.nextInt();
            if (guess == 7) {
                System.out.println("*** Correct! ***");
            } else {
                System.out.println("Sorry, that is wrong.");
            }
        }
    }
    

    5.2: Counting Applications

    Objectives

    At the end of the lesson the student will be able to:

    • Design and implement counting loops
    • Design and implement loops that accumulate values
    • Translate these designs into Java code

    5.2.1: Using Loops to Count

    • Assume that we are given the task of writing a loop that prints the numbers from 1 to 5
    • Thus, the program will display something like:
    • 1
      2
      3
      4
      5
      
    • Since we understand our problem, our next step is to write our algorithm
    • When designing a loop, you need to consider three things:
      1. Loop body -- what statements are repeated each time through the loop
      2. Loop termination condition -- how to stop looping
      3. Initialization code -- get started correctly
    • We start with the first task and design our loop body
    • We decide to use a variable named count and to increment the count each time the loop repeats
    • print out the count
      increment the count
      
    • Now we need to design how we stop looping (exit the loop)
    • We need a test condition for ending our loop when the count reaches 5
    • Working through our loop manually when the count is near 5, we see that our condition should be:
    • while count < 6
    • Now we move to the last task and ask ourselves what value the count variable must start with to print the first number correctly
    • We realize that we need to start the count variable at 1 to get the first number correct
    • set count = 1
    • Putting the pieces together we have:
    • set count = 1
      while count < 6
          print out the count
          increment the count
      
    • We test this manually and then translate it into Java code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public class Counter5 {
        public static void main(String[] args) {
            int count = 1; // initialize counter
            while (count < 6) { //loop condition
                //loop body
                System.out.println(count);
                count++; // adjust the counter
            }
            System.out.println("After loop count = " + count);
        }
    }
    

    5.2.2: Making Bar Graphs

    • Lets use our counting loop to make a horizontal bar graph
    • Our task is:
    • Write a program that asks a user for a number and then displays a horizontal bar graph using '*' characters. Use one '*' for each number.

    • For example:
    • Enter a number and I will display a bar graph.
      Enter your number: 5
      
      Your graph:
      *****
      
    • Since we understand our problem, our next step is to write our algorithm
    • We start with getting the user input
    • Prompt the user
      Get the number to graph
      
    • Now we need an algorithm to display the bar graph
    • Since we need to repeat something, we realize that we need to use a loop
    • Also, in a flash of inspiration, we realize that this problem is like our counting loop
    • We start our loop design by following the 3 steps:
      1. Loop body -- what statements are repeated each time through the loop
      2. Loop termination condition -- how to stop looping
      3. Initialization code -- get started correctly
    • First we decide what needs to be repeated during the loop
    • print out a '*'
      increment the count
      
    • For the next step, we look at our loop and choose the terminating condition
    • while count < number enter by the user
    • Finally we choose a value to start the count
    • set count = 0
    • Putting all the pieces together we have:
    • Prompt the user
      Get the number of stars to graph
      set count = 0
      while count < number of stars
          print out a '*'
          increment the count
      
    • We test this manually with a small number like 3 and then translate it into Java code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    import java.util.*;
    
    public class Graph {
        public static void main(String[] args) {
            Scanner input  = new Scanner(System.in);
    
            System.out.print("Enter a number and I will show"
                + " its bar graph.\nEnter your number: ");
            int number = input.nextInt();
    
            System.out.println("\nBar graph:");
            int count = 0;
            while (count < number) {
                System.out.print('*');
                count = count + 1;
            }
            System.out.println();
        }
    }
    

    5.2.3: Accumulating Values

    • One common looping task is to input a list of numbers and calculate their sum
    • For example, given the task:
    • Display the sum of the numbers from 1 through 5.

    • We start analyzing the problem by manually performing the task
    • sum = 1 + 2 + 3 + 4 + 5 = 15
    • As we look at the problem, we notice that the difference from one number to the next is just 1
    • In a flash of inspiration, we realize that this problem is like our counting loop
    • We need to count the numbers from 1 to 5
    • However, instead of printing the numbers, we need to add them to some variable
    • Since we understand our problem, our next step is to write our algorithm
    • We start our loop design by following the design 3 steps:
      1. Loop body -- what statements are repeated each time through the loop
      2. Loop termination condition -- how to stop looping
      3. Initialization code -- get started correctly
    • First we decide what needs to be repeated during the loop
    • sum = sum + count
      increment the count
      
    • Next we look at our loop and choose the terminating condition
    • while count <= 5
    • For the third step, we initialize both the variables used in the loop
    • set sum = 0
      set count = 1
      
    • Putting all the pieces together we have:
    • set sum = 0
      set count = 1
      while count <= 5
          sum = sum + count
          increment the count
      
    • We test this manually and find we forgot to display the sum after the loop
    • Display the sum after the loop
    • We add the missing step and then translate the algorithm into Java code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public class SumNums {
        public static void main(String[] args) {
            int sum = 0;
            int count = 1;
            while (count <= 5) {
                sum = sum + count;
                count = count  + 1;
            }
            System.out.println("Total sum: " + sum);
        }
    }
    
    • Testing the code we find the answer matches our manual calculations

    Calculating Products

    5.2.4: Running Totals

    • Let us look at how to accumulate numbers when we do not know how many numbers there are in the list
    • For example, given the task:
    • Display the sum of the numbers entered by a user. Display this sum after every number is entered. When the user enters a 0, show the total and exit the program.

    • We realize that this task is like our previous problem except that:
      1. We have to display the sum after every number is entered
      2. We do not know how many number the user will enter
    • The first change is easy -- we know how to print numbers!
    • For the second change, the specification gives us a hint
      • We exit the loop when the user enters a number
      • This is known as a sentinel-controlled loop
      • The sentinel is the value that tells us when to exit the loop
      • In this case, the sentinel value is the number 0
    • Since we understand our problem, our next step is to write our algorithm
    • We start our loop design by following the design 3 steps:
      1. Loop body -- what statements are repeated each time through the loop
      2. Loop termination condition -- how to stop looping
      3. Initialization code -- get started correctly
    • First we decide what needs to be repeated during the loop
    • Prompt the user
      Get the input
      sum = sum + input
      
    • Next we look at our loop and choose the terminating condition
    • while number != 0
    • For the third step, we initialize the variables used in the loop
    • set sum = 0
      set input = 0
      
    • We also need to display the sum after the loop terminates
    • Display the ending sum
    • Putting all the pieces together we have:
    • set sum = 0
      set input = 0
      while number != 0
          Prompt the user
          Get the input
          sum = sum + input
      Display the ending sum after the loop
      
    • We test this manually and find a problem!
      • Since number is initialized to 0, the program never enters the loop
    • We fix the problem, retest and translate the algorithm to Java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    import java.util.*;
    
    public class SumInput {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
    
            double data = 1.0;
            double sum = 0.0;
            while (data != 0.0) {
                System.out.print("So far, sum = " + sum
                    + "\nEnter a number or 0 to exit: ");
                data = input.nextDouble();
                sum = sum + data;
            }
            System.out.println("Ending sum: " + sum);
        }
    }
    

    Averaging the Tally

    • An average is calculated by summing a quantity of numbers and then dividing by the count
    • What would we add to the code to display the average of the numbers that were entered?

    5.2.5: Common Loop Pitfalls

    Infinite Loops

    • Common error: unintentional infinite loop
    • For example, what is wrong with the following code?
    1
    2
    3
    4
    5
    6
    7
    8
    
    public class InfiniteLoop1 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10) {
                System.out.println(count); // trace
            }
        }
    }
    

    Empty Statements

    • Remember that statements are terminated by a semicolon
    • Is the following a legal statement?
    • ;
    • Known as an empty or null statement
    • Empty statements are a common source of infinite loops
    • For example, what is wrong with the following code?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    public class InfiniteLoop2 {
        public static void main(String[] args) {
            int count = 0;
            while (count < 10); {
                System.out.println(count); // trace
                count++;
            }
        }
    }
    

    Off-By-One Errors

    • A common looping problem is the off-by-one error
    • Often a less-than is confused with a less-than-or-equal-to
    • For example, to sum the numbers from 1 to 5, what is wrong with:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public class OffByOne {
        public static void main(String[] args) {
            int sum = 0;
            int count = 1;
            while (count < 5) {
                sum += count;
                count++;
            }
            System.out.println(sum);
        }
    }
    

    Tracing Variables

    • One good way to discover loop errors is to display the variables that change in the loop
    • Tracing variables means watching their values change as the program executes
    • You can insert temporary output statements in your program
    • System.out.println("count=" + count + ", sum=" + sum);
      
    • For instance, we had trace statements in the infinite loop examples above

    5.2.6: Summary

    • One common use for loops is to count numbers
    • We saw several applications for loops that count in this section
      • Counting loops
      • Making bar graphs
      • Summing numbers
    • We also used accumulation loops in this section to sum, or find the product of, a list of numbers
    • Once you understand a programming problem that needs a loop, you design the loop in 3 steps
      1. Loop body -- what statements are repeated each time through the loop
      2. Loop termination condition -- how to stop looping
      3. Initialization code -- get started correctly
    • Several problems that can occur when using a loop
      • Infinite loops: loops that "never" end
      • Off-by-one errors: starting or stopping at a wrong value
    • Tracing variables is a good way to discover loopy errors

    Check Yourself

    1. What are the parts of any loop?
    2. How do you code a counting loop?
    3. How do you code a loop to display horizontal bar graphs?
    4. How do you code a loop to accumulate values?
    5. How do you code a loop to keep a running total of numbers entered by a user?
    6. What are some common looping errors and how can you recognize them?

    Exercise 5.2

    Background

    Recall from lesson 4.1.5 that you can add numbers to a char data type. Also recall that you can cast a char to an int to get its numerical equivalent.

    Specifications

    1. Save the following code as Ascii.java
    2. Modify the code to list the integer count and ASCII characters numbered from 1 through 255 like the following excerpt:
    3. 65: A
      66: B
      67: C
      
    4. Submit your program along with your other exercises for this lesson.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    public class Counter5 {
        public static void main(String[] args) {
            int count = 1; // initialize counter
            while (count < 6) { //loop condition
                //loop body
                System.out.println(count);
                count++; // adjust the counter
            }
            System.out.println("After loop count = " + count);
        }
    }
    

    One possible answer.

    5.3: Predefined Methods

    Objectives

    At the end of the lesson the student will be able to:

    • Create code that calls predefined methods
    • Describe the flow of control of a method call
    • Explain why some methods can be used in expressions and why some cannot
    • Write code that generates random numbers

    5.3.1: About Methods

    Method -- a subprogram (function, procedure or subroutine) that executes a block of code when called.

    • Java has two types of methods: instance methods and static methods
    • To use an instance method, you must first create an object
      Scanner input = new Scanner(System.in);
    • After creating the object, you can call a method of the object
    • You call a method by using the object name, a dot (period), the method name and a set of parenthesis
    • double number = input.nextDouble();
    • To use a static method, you use the name of the class instead of an object
    • double number = Math.sqrt(9.0);
    • You code the method call much the same way no matter if it is an instance method or a static method
    • The only difference is whether you start with an object name or a class name

    5.3.2: Calling Methods

    • Calling a method is like a boss asking a worker to do something
    • In programming, the "boss" method asks a "worker" method to complete a task
    • To ask a method to do something, the "boss" method uses a method call
    • A method call consists of the method name and any parameters the method may need to do its task
    • For example, to calculate the square root of a number, you would call the sqrt() method:
    • Math.sqrt(9.0);
    • When called with an argument of 9.0, the method returns a value of 3.0
    • Some methods do not return a value, but just perform a task
    • For example:
    • System.out.println("Hi Mom!");
    • The method prints the letters "Hi Mom!" to the console but does not return any values

    5.3.3: Flow of Control for a Method Call

    • To use methods well, you must understand their flow of control
    • Consider the two method calls in the example shown below
    1
    2
    3
    4
    5
    6
    
    public class MethodCaller {
        public static void main(String[] args) {
            double result = 1 + Math.sqrt(9.0);
            System.out.println(result);
        }
    }
    

    Flow for Methods that Return a Value

    • The program starts executing in the main() method
    • The next line is an assignment statement, so the right-hand side is evaluated first
    • 1 + Math.sqrt(9.0)
    • The program evaluates the method call first since it has higher precedence than addition
    • When making the method call, the computer stops working on the current code and instead works on the code inside the method
    • The computer sends the information inside the parenthesis of the method call to the method
    • The method uses the data it was passed to perform its calculations
    • When the method is done, it returns the result of its calculation back to the code that called the method
    • The computer then uses the returned value to complete the computation
    • When the right-hand side is done, the value of the computation is saved in the variable result

    Flow for Methods That Do Not Return a Value

    • The next line of code uses the println() method, which does not return a value
    • Like the previous method call, the computer stops working on the current code
    • The computer sends the information inside the method call parenthesis to the method
    • System.out.println(result);
    • The method uses the data it was passed to complete its task
    • When the method completes its task, the computer goes back to the code that called the method
    • However, the method does not return a value when it goes back
    • Instead, the computer advances to the next statement after the method call and continues the program
    • Since the method does not return a value, you cannot use it in an expression
    • Methods calls that do NOT return a value must be coded as a separate statement

    5.3.4: Generating Random Numbers

    • For another example of predefined methods, lets us look at random numbers
    • Random numbers are a series of numbers whose order cannot be predicted
    • Many computational problems need to use random numbers
    • Hard to find truly random numbers, even in real life
      • Dice are never perfect
      • Cards are never shuffled completely randomly
      • Computers can only handle numbers within a finite range and limited precision
    • The best that can be done in most cases is to generate pseudorandom numbers
      • Sufficiently random for the task at hand
    • Math.random() is a library method that produces series of psuedorandom numbers
      • Range is 0.0 up to, but not including, 1.0 (0.999...)
      • Returns a "random" double-precision value
    • For example:
    • System.out.println(Math.random());

    5.3.5: Example Use of Random Numbers: Dice Simulation

    • Let us apply the Math.random() method to the problem of simulating a die roll
    • We need a number between 1 and 6, but Math.random() returns a number between 0.0 and 0.99...
    • Since we need 6 random values, we multiply the value that Math.random() produces by 6.
    • Also, we need an integer, so we cast the result to an int
    • (int) (Math.random() * 6)
    • Now we can generate random integer numbers between 0 and 5
    • To get a number between 1 and 6, we shift the numbers by adding 1
    • Our code to simulate a single die with random numbers is now:
    • int die = 1 + (int) (Math.random() * 6);
      System.out.println("You rolled a " + die);
      
    • We can generalize our formula for producing integer random numbers to:
    • STARTING_VALUE + (int) (Math.random() * SCALING_FACTOR);
      
    • Let us use our code to simulate rolling a pair of dice
    1
    2
    3
    4
    5
    6
    7
    8
    
    public class DiceRoller {
        public static void main(String[] args) {
            int die1 = 1 + (int) (Math.random() * 6);
            int die2 = 1 + (int) (Math.random() * 6);
            System.out.println("You rolled a " + die1
                + " and a " + die2);
        }
    }
    
    • Note how the program simulates rolling 2 dice using 1 die at a time
    • You would get a different result if you just generated a random number between 2 and 12
    • What would you change to roll the two dice 10 times?

    5.3.6: Summary

    • A method is a block of code get executed when called
    • Java has two types of methods: instance methods and static methods
    • To use an instance method, you must first create an object
      Scanner input = new Scanner(System.in);
    • After creating the object, you can call a method of the object
    • double number = input.nextDouble();
    • To use a static method, you use the name of the class instead of an object
    • double number = Math.sqrt(9.0);
    • Java supports methods that return a value and those that do not
    • Methods calls that return a value can be used inside of expressions
    • Methods calls that do NOT return a value require a separate statement
    • As an example of predefined methods, we looked at Math.random()
    • We used this method to simulate the rolling of a die
    • int die = 1 + (int) (Math.random() * 6);
      System.out.println("You rolled a " + die);
      

    Check Yourself

    1. What is a method?
    2. How do you call a method?
    3. What is a random number?
    4. How do you code a random number that simulates rolling a die?

    Exercise 5.3

    In this exercise we look at the randomness of the Math.random() method.

    1
    2
    3
    4
    5
    6
    7
    8
    
    public class DiceRoller {
        public static void main(String[] args) {
            int die1 = 1 + (int) (Math.random() * 6);
            int die2 = 1 + (int) (Math.random() * 6);
            System.out.println("You rolled a " + die1
                + " and a " + die2);
        }
    }
    

    Specifications

    1. Save the code as DiceRoller.java
    2. Change the code by adding a loop that rolls the two dice 10 times.
    3. Display the output of the roll each time through the loop.
    4. Submit your program along with your other exercises for this lesson.

    Example Output

    You rolled a 1 and a 1
    You rolled a 4 and a 5
    You rolled a 5 and a 6
    You rolled a 3 and a 6
    You rolled a 2 and a 4
    You rolled a 4 and a 6
    You rolled a 3 and a 4
    You rolled a 1 and a 5
    You rolled a 4 and a 5
    You rolled a 4 and a 6
    

    5.4: Coding Methods

    Objectives

    At the end of the lesson the student will be able to:

    • Defining methods
    • Pass arguments to methods
    • Return a value from a method
    • Describe what is meant by a local variable

    5.4.1: Defining Methods

    • Rather than using a predefined method, you can write your own methods
    • Writing methods becomes more important as your programs become larger
    • The reason is that writing small programs is easier than writing large programs
      • Writing a 20 line program is easier than writing a 1000 line program
    • We can write, test and understand small methods independently of one other
    • These correctly working methods become the building blocks of larger programs
    • We use these "building-block" methods to make a larger program

    Syntax

      returnType methodName(type1 param1, type2 param2, ...) {
          ...
      }
      
    • The returnType is the type of data that the method returns
      • Return types include: char, int, double, String, etc.
      • A method can return any data type or none at all
      • A method returning no values uses the special return type: void
    • After specifying the return type, you give the method a name
    • Following the name, add a set of parentheses ()
    • Within the parenthesis specify the parameters for any arguments passed by the method call
    • The block of code executed by the method is enclosed in the curly braces
    • Note that the first line of a method is called the method heading
    • The code within the curly brackets is called the method body

    For Example

    • The following code defines two simple methods
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      
      public class Square5 {
          public static void main(String[] args) {
              double number = 5;
              double result = square(number);
              System.out.println(result);
          }
      
          static double square(double number) {
              double result = number * number;
              return result;
          }
      }
      
    • Method main() calls method square(), passing the value of the variable number
    • This value gets copied to the parameter named number
    • A parameter is a variable that get initialized from the method call
    • Method square() uses the parameter to compute the result and then returns that result

    Static Methods

    • Note the keyword static in the method heading
    • Until we cover objects, all our methods must use the qualifier static
    • If you forget the static keyword, you get a message like:
    non-static method cannot be referenced from a static context
    

    5.4.2: Passing Arguments

    • When a program makes a method call, it sends the information inside the parenthesis to the method
    • square(number)
    • The value of each argument is copied to its corresponding parameter
    • static double square(double number) {
          ...
      }
      
    • The method call must include an argument for every parameter
    • In addition, the data type of each argument must be compatible with the data type of the parameter
    • Thus, in our previous example, the data type of the variable number must be compatible with the data type of the parameter number
    • Recall that Java will automatically change some data types to another type
    • byte => short => int => long => float => double
                      /
               char =/
      
    • You can specify zero, one or more parameters for a method
    • To code multiple parameters, you separate them with a comma
    • returnType methodName(type1 param1, type2 param2, ...) {
          ...
      }
      

    For Example

    • Following program has a method named pow()for calculating powers of numbers with positive int exponents
    • Method pow() has two parameters: base and exponent
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    public class Power {
        public static void main(String[] args) {
            double value = pow(2, 3);
            System.out.println(value);
        }
    
        static double pow(double base, int exponent) {
            if (exponent == 0) {
                return 1;
            }
            int loopCounter = 1;
            double result = base;
            while (loopCounter < exponent) {
                result = result * base;
                loopCounter++;
            }
            return result;
        }
    }
    

    Common Pitfall

    • Common Mistake: declaring parameters 'again' inside a method:
    • double pow(int base, int exponent) {
          int loopCounter;  // local variable
          int base;         // NO!
      }
      
    • Compiler error: variable "already defined"
    • Power.java:21: base is already defined in pow(double,int)
          int base;         // NO!
              ^
      
    • Parameters ARE local variables -- except they are initialized from arguments in the method call

    5.4.3: Returning a Value

    • Methods that return a value must execute a return statement
    • For instance, in our original example, method square() had a return statement
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    public class Square5 {
        public static void main(String[] args) {
            double number = 5;
            double result = square(number);
            System.out.println(result);
        }
    
        static double square(double number) {
            double result = number * number;
            return result;
        }
    }
    

    void Return Types

    • You can write methods that do not return values by using a void return type
    • Note that method main() has a void return type
    • A return statement is optional if no value is returned
    • Instead, the return occurs automatically at the end of the method

    Exiting Early

    • Sometimes you do not want to execute all the code in a method
    • You can use a return statement anywhere to end a method call and return
    • Control returns immediately from a method when a return statement is executed
    • We saw this in our second example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    public class Power {
        public static void main(String[] args) {
            double value = pow(2, 3);
            System.out.println(value);
        }
    
        static double pow(double base, int exponent) {
            if (exponent == 0) {
                return 1;
            }
            int loopCounter = 1;
            double result = base;
            while (loopCounter < exponent) {
                result = result * base;
                loopCounter++;
            }
            return result;
        }
    }
    

    5.4.4: Local Variables and Scope

    • Variables and parameters declared in a method can only be used within that method
    • This is known as a variables scope
    • When the method finishes executing, local variables disappear
    • Trying to use a local variable outside a method cause a compile error

    For Example

    • Using our second example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    public class Power {
        public static void main(String[] args) {
            double value = pow(2, 3);
            System.out.println(value);
        }
    
        static double pow(double base, int exponent) {
            if (exponent == 0) {
                return 1;
            }
            int loopCounter = 1;
            double result = base;
            while (loopCounter < exponent) {
                result = result * base;
                loopCounter++;
            }
            return result;
        }
    }
    
    • The local variable exponent declared in method pow() cannot be used inside the main() method
    • For instance, if we tried to print the variable exponent in main()
    • public static void main(String[] args) {
          double value = pow(2, 3);
          System.out.println(value);
          System.out.println(exponent);
      }
      
    • We would get a compiler error like:
    • Power.java:5: cannot find symbol
      symbol  : variable exponent
      location: class Power
              System.out.println(exponent);
                                 ^
      

    5.4.5: Programming Style Requirements for Methods

    • Consider again our first example
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    public class Square5 {
        public static void main(String[] args) {
            double number = 5;
            double result = square(number);
            System.out.println(result);
        }
    
        static double square(double number) {
            double result = number * number;
            return result;
        }
    }
    
    • Note the placement of the curly braces
    • When making up a name for a method, use verbs since methods perform an action
    • In addition, start method names with a lower case letter
    • For your homework, every method must have a block comment before the name
    • OK if formal parameter names are the same as argument names

    Example of Fully Commented Method

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    /**
     * CS-12J Asn 3
     * Square5.java
     * Purpose: Print the square of the number 5.
     *
     * @author Ed Parrish
     * @version 1.0 9/28/05
     */
    public class Square5 {
        public static final int NUMBER = 5;
    
        /**
         * The main method of the program.
         *
         * @param args Not used.
         */
        public static void main(String[] args) {
            double number = NUMBER;
            double result = square(number);
            System.out.println(result);
        }
    
        /**
         * Calculate the square of a number.
         *
         * @param number The number to square
         * @return The square of the number.
         */
        static double square(double number) {
            double result = number * number;
            return result;
        }
    }
    
    • Note the correct way to write a constant in Java
    • public static final int NUMBER = 5;

    Using CheckStyle

    • It is tedious to check your code for programming style
    • Instead, you can use your computer to accomplish the task
    • Use a program named CheckStyle
      • Free and open source
      • Used for major Java projects like Jakarta
    • I provide instructions for installing and using CheckStyle for both jEdit and TextPad

    Further Information

    5.4.6: Summary

    • Writing methods is an important technique for breaking up your code into understandable pieces
    • Methods are declared by specifying a return type, name and a list of parameters
    • static double pow(double base, int exponent) {
          ...
      }
      
    • Values are passed to a method by putting values of a compatible type, in the same order, inside the parentheses of the method call
    • pow(2, 3);
    • Methods return a value using a return statement
    • return result;
    • Variables and parameters declared in a method can only be used within that method
    • When the method finishes executing, local variables disappear
    • Trying to use a local variable outside a method causes a compiler error
    • Methods have style requirements you must follow
    • For instance, you must have a block comment before the name
    • To check you style, you can use Checkstyle

    Check Yourself

    1. How does writing methods contribute to good programming?
    2. What is the syntax for writing methods?
    3. What is meant by the term argument? parameter?
    4. What statement is used to return values from methods?
    5. Why should block comments be placed before method headings?
    6. What makes up a block comment for methods?

    Exercise 5.4

    The absolute value of a number is the number itself if the number is positive and the negative of the number if the number is negative. For instance, the absolute value of 1 is 1 and the absolute value of -1 is also 1.

    The following code is the start of a program to convert numbers to their absolute value. You need to complete the program by finishing the calcAbs() method.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    import java.util.Scanner;
    
    public class AbsValueMaker {
        public static void main(String[] args) {
            Scanner input  = new Scanner(System.in);
    
            System.out.print("Number to convert: ");
            double num = input.nextDouble();
    
            System.out.println("Absolute value is: "
                + calcAbs(num));
        }
    
        public static double calcAbs(double numToConvert) {
            // Insert statements here
    
            return 0; // change the return statement too!
        }
    }
    

    Specifications

    1. Save the above code as AbsValueMaker.java
    2. Complete the program by writing a method named calcAbs() that accepts a parameter of type double, computes the absolute value of the parameter, and returns the absolute value.
    3. Submit your program along with your other exercises for this lesson.

    Wrap Up

    Home | WebCT | Announcements | Schedule | Expectations | Course info
    Help | FAQ's | HowTo's | Links

    Last Updated: October 09 2005 @18:10:09