S-111
  • Home
  • Lectures
  • Problem Sets
  • Sections
  • Syllabus
  • Schedule
  • Staff
  • Resources
  • Canvas
  • Ed Discussion
  • Gradescope

Section 4

  • Bug of the Day
  • Review exercises
    • Methods that return values
  • Java exercises
  • Additional exercises

Bug of the Day

Suppose we have written the following “helper” method whose function is to compute the average of two integers.

public static double computeAverage(int a, int b, double avg) {
    avg = (a + b) / 2.0;
    return avg;
}

We then use this method in the following code fragment:

int a = 4;
int b = 9;
double avg = 0.0;
computeAverage(a, b, avg);
System.out.println(avg);

This code should output 6.5, but it does not. Identify the bug in the code and suggest a fix.

Review exercises

Recall from lecture what you learned about methods that take parameters and return values.

  1. What is a parameter to a method? 1
  2. What is the difference between a formal parameter and an actual parameter? 2
  3. Describe the syntax of a method that takes two integers as parameters. How should the method header be written? 3
  4. Demonstrate the process of making an entire method call, from parameter evaluation to the method returning. 4
  5. Describe the scope rules of method parameters. 5

  6. Given the following program, we will step through its execution to obtain the final output. Be careful! This example is designed to confuse you! 6

    public class MysterySoda {
        public static void main(String[] args) {
            String soda = "coke";
            String pop = "pepsi";
            String pepsi = "soda";
            carbonated(soda, pop, pepsi);
        }

        public static void carbonated(String coke, String soda, String pop) {
            System.out.println("say " + soda + " not " + pop + " or " + coke);
        }
    }

Methods that return values

Recall that, so far, we described a method as a way to capture the structure of a program by breaking tasks into subtasks and eliminating code duplication. Return values extend the functionality of a method by allowing it to produce a single value as the result of its work. Together with parameters, methods can now behave more like functions from mathematics: their return values can depend on their parameters, allowing us to further break down a task into a function that behaves flexibly given different inputs.

The opposite() method from lecture has been reproduced below.

public static int opposite(int number) {
    return number * -1;
}
  1. Which part of the method header describes the method’s return type? 7

  2. Which part of the method actually defines the return value? 8

  3. Consider the following code fragment.

    int points = 10;
    int penalty = opposite(points);
    

    Show how the code would be executed, line by line. Include the work done inside the opposite() method, and show how the value returned by the method replaces the call. 9

Java exercises

  1. Given the more challenging version of MysterySoda below, determine the output of the program by tracing it on paper or on the board. Then check your answer by running it in VSCode. 10

    public class MysteryJuice {
        public static void main(String[] args) {
            String orange = "juice";
            String apple = "tasty";
            String juice = "apple";
            String tasty = "orange";
            String yum = juice;
    
            fresh(apple, juice, orange);
            fresh(orange, tasty, tasty);
            fresh("juice", juice, "grape");
            fresh(yum, "yum", apple);
        }
    
        public static void fresh(String juice, String orange, String tasty) {
            System.out.println("yum " + orange + " juice " + tasty + " and " + juice);
        }
    }
    
  2. Consider the unfinished class VoidOrNonVoid below.

    public class VoidOrNonVoid {
    
        /*
         * getProduct: This method accepts two int parameters and returns their
         * product as an int.
         */
        public static ______ getProduct(_____, _____) {
            return x * y;
        }
    
        /*
         * printProduct: This method accepts two int parameters and prints their
         * product.
         */
        public static _____ printProduct(_____, _____) {
            System.out.println(x + " * " + y + " = " + (x * y));
        }
    
        public static void main(String[] args) {
            int a = 5;
            int b = 8;
    
            int p1 = getProduct(a, b);              // #1
    
            int p2 = 10 + getProduct(a, b);         // #2
    
            System.out.println(getProduct(a, b));   // #3
    
            getProduct(a, b);                       // #4
    
            int p3 = printProduct(a, b);            // #5
    
            int p4 = 10 + printProduct(a, b);       // #6
    
            System.out.println(printProduct(a, b)); // #7
    
            10;                                     // #8
    
            printProduct(a, b);                     // #9
        }
    }
    
    1. Fill in the blanks to complete the method signatures of the getProduct() and printProduct() methods in the code above. Hint: one method should have a non-void return type and one should have a void return type. 11
    2. Given the method declarations above, decide whether each of the labeled statements will compile. If a statement will compile, describe what the effect of that statement is (what is the output, or how does a variable change?). If a statement will not compile, explain why. 11
  3. Using the following template, write a method called printNumbers that accepts three integer parameters — min, max and numCopies — and prints numCopies copies of each integer from min to max, with each integer sequence on its own line. 12

    For example, the call printNumbers(3, 6, 5) should produce the following output:

    33333
    44444
    55555
    66666
    

    Copy the following code template into a new Java file.

    public class NumberTwelve {
        /*
         * printNumbers - prints numCopies copies of the integers
         * from min to max, with each integer on its own line
         */
        public static ________ printNumbers(___________________) {
    
        }
    
        public static void main(String[] args) {
            // Add code below that uses the method that you write.
    
        }
    }
    

Additional exercises

  1. Determine the output of the following program. Draw tables for each scope that appears during the execution of the program. Use paper or the classroom’s board. After you finish your trace, you can check your work by running the program in VSCode. 13
    public class MysteryReturn {
        public static int mystery(int a) {
            System.out.println("a = " + a);
            int b = 7 - 2*a;
            return b;
        }
    
        public static void main(String[] args) {
            int a = 5;
            int b = 2;
            System.out.println(a + " " + b);
    
            a = mystery(b);
            System.out.println(a + " " + b);
    
            System.out.println(mystery(a));
            System.out.println(a + " " + b);
    
            mystery(4*b - 1);
            System.out.println(a + " " + b);
        }
    }
    

  1. A parameter is a variable defined as part of the method header that can be “filled” at the time of the method call, such that the value gets its own name and scope in the called method. ↩

  2. The formal parameters of a method is the list of variables in the method header. At the time of the method call, the actual parameters are listed in parentheses to the right of the method name. ↩

  3. Let’s say the method is called myMethod. Then the method header would look like the following:

    public static void myMethod(int a, int b) { ...
    

    ↩

  4. The very first thing that happens is the evaluation of the actual parameters (or arguments) to the method. Then, each argument is supplied to the method in the order they were listed. A new scope is created for the called method, in which the values of the arguments are given names described by the formal parameters. Then the body of the method runs to completion, and the method’s scope is removed, along with any local variables in the method. The flow of control then returns to the calling method. ↩

  5. Like for loops, the variables specified in the parentheses of the method (the formal parameters) are declared outside the curly braces of the method, but the parameters’ scope is limited to the method itself. Therefore the parameters are not accessible outside the method. In addition, when a method is called, the calling method’s variables are not accessible by the method that is being called. (This is called lexical scoping — some programming languages have different scope rules in this regard.) ↩

  6. Here’s the table of values for the main() method:

    soda pop pepsi
    "coke" "pepsi" "soda"

    The call carbonated(soda, pop, pepsi) turns into carbonated("coke", "pepsi", "soda") when the actual parameters are evaluated. Then, that call has the following table of values:

    coke soda pop
    "coke" "pepsi" "soda"

    Therefore the System.out.println(...) statement produces the following output:

    say pepsi not soda or coke
    

    ↩

  7. In the method header public static int opposite(int number) { ..., the first int, between the public static and the opposite identifier, is the method’s return type. ↩

  8. In the method body, the expression to the right of the return statement specifies the value returned by the method. The expression must have the same type as the specified return type. ↩

  9. The table below shows the code’s execution.

    Step Effects of code
    1 The points variable gets the value 10.
    2 The assignment to penalty is encountered.
    3 The right side of the assignment is evaluated.
    4 In order to call the method, the points expression is evaluated.
    5 opposite(10) runs.
    6 The return statement is evaluated.
    7 opposite(10) returns -10.
    8 penalty gets the value -10.

    ↩

  10. The output is included below.

    yum apple juice juice and tasty
    yum orange juice orange and juice
    yum apple juice grape and juice
    yum yum juice tasty and apple
    

    ↩

  11. The correct methods are included below.

    /*
     * getProduct: This method accepts two int parameters and returns their
     * product as an int.
     */
    public static int getProduct(int x, int y) {
        return x * y;
    }
    
    /*
     * printProduct: This method accepts two int parameters and prints their
     * product.
     */
    public static void printProduct(int x, int y) {
        System.out.println(x + " * " + y + " = " + (x * y));
    }
    

    The compilability of each statement is included in the table below.

    Statement Compiles? Effect or reasoning
    1 yes p1 gets the value 40.
    2 yes p2 gets the value 10 + 40 = 50.
    3 yes 40\n is printed.
    4 yes 40 is returned, but the value is lost.
    5 no printProduct() does not return anything.
    6 no printProduct() does not return anything.
    7 no printProduct() does not return anything.
    8 no 10 is not a statement.
    9 yes 5 * 8 = 40\n is printed.

    ↩

  12. The printNumbers() method is included below.

    /*
     * printNumbers - prints numCopies copies of the integers
     * from min to max, with each integer on its own line
     */
    public static void printNumbers(int min, int max, int numCopies) {
         for (int i = min; i <= max; i++) {
              for (int j = 0; j < numCopies; j++) {
                   System.out.print(i);
              }
              System.out.println();
         }
    }
    

    ↩

  13. The output is included below.

    5 2
    a = 2
    3 2
    a = 3
    1
    3 2
    a = 7
    3 2
    

    ↩

Last updated on June 30, 2025.