CPSC 124, Fall 2017: Sample Answers to Quiz #4

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. A subroutine can be declared to be public or private. Briefly explain the difference.

Answer. If a subroutine is declared "private", then it can only be used in the same class that contains the definition of the subroutine. If it is private, then it can also be used in any other class (but in another class, it must use its full name, which includes the name of the class where it is defined.)

Question 2. What happens when the computer executes this statement:    return ans;

Answer. When the computer executes "return ans;", the subroutine that is being executed is terminated immediately, and the value of the variable ans is returned as the value of that subroutine. The value is returned to the place in the program where the subroutine was called.

(This statement would have to occur in a subroutine that has a return type (that is not void), and the type of the variable ans would have to be compatible with the return type.)

Question 3. A subroutine is a kind of "black box.'' Explain what this means and why it is important when writing complex programs.

Answer. A ``black box'' is just something that can be used without understanding how it works internally. A subroutine performs some task. You can call the subroutine to perform that task without worrying about the details of how it actually does it. You need to know the interface of the subroutine, but not its implementation.

This is important when writing complex programs because it means that you don't have to think about all of the details of the program at once. You can break down a big, complex program into simpler subroutines, and you can work on each subroutine as an independent problem. Also, you can often find subroutines that have already been written that you can use in your program without having to understand exactly how they work.

Question 4. Write a subroutine named stars that will output a line of stars to standard output, using System.out. (A "star" means the character '*'.) The number of stars should be given as a parameter to the subroutine. You will need a loop. For example, the statement "stars(25)" would output:   *************************


public static void start( int numberOfStars ) {
    for (int i = 0; i < numberOfStars; i++) {
        System.out.print( '*' );

("public" and "static" are not required parts of the answer, nor is the end-of-line at the end.)