Docsity

Computer Science I: Static Methods and Recursion - Prof. Jennifer E. Walter, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 14—Looking Ahead
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Recursion
C H A P T E R 1 4 (Section 1)
The best way to predict the future is to invent it.
—Alan Kay, Xerox Palo Alto Research Center, 1972
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
Static Methods
•Methods called by using the dot operator as a suffix on the
class name
• Examples of static methods we've used
oCharacter class methods
oMath class methods
These methods are usually public, meaning they're exported for
use by other classes.
Static methods depend only on input parameters and cannot use
any instance variables or non-static methods within the class.
Client classes can call these methods without creating an object
of the class type.
Static Methods
• Static methods are declared using the following syntax
public static <return-type> <method-name>(<parameter list>)
One static method used in every program is the main method.
Since main is a static method, it must create a new object of its
own class type before it can call any non-static methods.
Static methods cannot access instance variables or instance
methods and cannot contain the keyword "this", because they
apply to an entire class, not to a particular object in a class.
Static Methods
An advantage of writing static methods is that they can be easily
tested from the DrJava Interactions Pane.
For example, try typing
Character.toUpperCase('c')
or
Math.pow(2,6)
in the Interactions Pane.
The recursive methods we will write and test in our next
programs can be static because they generally depend only on
the value of their instance variables.
Reading and Printing without acm
To read from the keyboard without using the acm package, you
can import java.util and use the Scanner class:
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
To print to the screen, use:
System.out.println("Text to output.");
Recursion
•Recursion is the process of solving a problem by dividing it
into smaller subproblems -- of the same form.
• 2 types of recursion we will study:
oGenerative Recursion: Usually implemented by a static method
containing a call to itself. The number of repetitions is controlled by an
integer parameter. This is an alternative to while and for-loops.
oStructural Recursion: Implemented with "recursive classes", i.e. classes
that contain instance variables of their own type. (We will cover this topic
next.)
pf3
pf4

Partial preview of the text

Download Computer Science I: Static Methods and Recursion - Prof. Jennifer E. Walter and more Study notes Computer Science in PDF only on Docsity!

Chapter 14—Looking Ahead

The Art and Science of

An Introduction to Computer Science ERIC S. ROBERTS

Java

Recursion

C H A P T E R 1 4 (Section 1)

The best way to predict the future is to invent it.

—Alan Kay, Xerox Palo Alto Research Center, 1972

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

Static Methods

• Methods called by using the dot operator as a suffix on the

class name

• Examples of static methods we've used

o Character class methods

o Math class methods

These methods are usually public, meaning they're exported for

use by other classes.

Static methods depend only on input parameters and cannot use

any instance variables or non-static methods within the class.

Client classes can call these methods without creating an object

of the class type.

Static Methods

• Static methods are declared using the following syntax

public static <return-type> <method-name>()

One static method used in every program is the main method.

Since main is a static method, it must create a new object of its

own class type before it can call any non-static methods.

Static methods cannot access instance variables or instance

methods and cannot contain the keyword "this", because they

apply to an entire class, not to a particular object in a class.

Static Methods

An advantage of writing static methods is that they can be easily

tested from the DrJava Interactions Pane.

For example, try typing

Character.toUpperCase('c')

or

Math.pow(2,6)

in the Interactions Pane.

The recursive methods we will write and test in our next

programs can be static because they generally depend only on

the value of their instance variables.

Reading and Printing without acm

To read from the keyboard without using the acm package, you

can import java.util and use the Scanner class:

Scanner sc = new Scanner(System.in);

int number = sc.nextInt();

To print to the screen, use:

System.out.println("Text to output.");

Recursion

• Recursion is the process of solving a problem by dividing it

into smaller subproblems -- of the same form.

• 2 types of recursion we will study:

o Generative Recursion : Usually implemented by a static method

containing a call to itself. The number of repetitions is controlled by an

integer parameter. This is an alternative to while and for-loops.

o Structural Recursion : Implemented with "recursive classes", i.e. classes

that contain instance variables of their own type. (We will cover this topic

next.)

Recursive Functions

• The easiest examples of recursion to understand are functions

in which the recursion is clear from the definition. As an

example, consider the factorial function, which can be defined

in either of the following ways:

n! = n

x

( n - 1)

x

( n - 2)

x

x

x

x

n! =

n

x

( n - 1)!

if n is 0

otherwise

• The second definition leads directly to the following code,

which is shown in simulated execution on the next slide:

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

Simulating the factorial Method

skip simulation

Factorial

Enter n: 5

5! = 120

public static void calcFactorial() {

int n = this.readInt("Enter n: ");

println(n + "! = " + factorial(n) );

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

private int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

public static int factorial(int n) {

if (n == 0) {

return 1;

} else {

return n * factorial(n - 1);

n

The Recursive “Leap of Faith”

• The purpose of going through the complete decomposition of

the calculation of factorial(5) is to convince you that the

process works and that recursive calls are in fact no different

from other method calls, at least in their internal operation.

• Writing recursive programs becomes natural only after you

have enough confidence in the process that you don’t need to

trace them fully.

• As you write a recursive program, it is important to believe

that any recursive call will return the correct answer as long

as the arguments continually get closer to a stopping

condition.

• Believing that to be true—even before you have completed

the code—is called the recursive leap of faith.

Shades of Indiana

Jones, Batman!!

The Recursive Paradigm

• Most recursive methods you encounter in an introductory

course have bodies that fit the following general pattern:

if ( test for one or more base cases ) {

Compute and return the simple solution without using recursion.

} else {

Divide the problem into one or more subproblems that have the same form.

Solve each of the subproblems by calling this method recursively.

Return the solution from the results of the various subproblems.

• Finding a recursive solution is mostly a matter of figuring out

how to break it down so that it fits the paradigm. When you

do so, you must do two things:

  1. Identify base cases that can be solved without recursion.

Find a recursive decomposition that breaks each instance of

the problem into simpler subproblems of the same type, which

you can then solve by applying the method recursively.

The Recursive Paradigm

• What does "a base case" mean? It can be any condition that

stops the recursion by returning a value. Each recursive call

must ensure that the input argument is closer to the base case

than the current input parameter.

if ( test for a base case ) {

Compute and return the solution without using recursion.

} else {

Divide the problem into one or more subproblems that have the same form.

Solve each of the subproblems by calling this method recursively.

Return the solution from the results of the various subproblems.

Recursive Methods

• Write a recursive method to return the sum of all the numbers

between 1 and n

public static int recSum(int n) {

if (n == 0) {

return 0;

} else {

return n + recSum(n-1);

In this example, the stopping case is reached when the

input parameter n is equal to 0.

Testing Recursive Methods

• What test cases would you use to thoroughly test this method?

public void run() {

String str1 = "rotator"; // odd length palindrome

String str2 = ""; // empty palindrome

String str3 = "maddam"; // even length palindrome

String str4 = "gomjabber"; // non-palindrome

println(str1+ " should be a palindrome and tests "+

isPalindrome(str1));

println(str2+ " should be a palindrome and tests "+

isPalindrome(str2));

println(str3+ " should be a palindrome and tests "+

isPalindrome(str3));

println(str4+ " should not be a palindrome and tests "+

isPalindrome(str4));

Recursive Methods

• Write a recursive predicate method that takes an array of

integers as an input parameter and returns true if the numbers

in the array are all even.

public static boolean allEven(int[] arr, int i) {

if (i == arr.length) {

return true;

} else {

return (arr[i] % 2 == 0) && allEven(arr,i+1);

Recursive Methods

• Write a recursive predicate method that takes an array of

integers as an input parameter and returns true if any of the

numbers in the array list are even.

private boolean anyEven(int[] arr, int i) {

if (i == arr.length) {

return false;

} else {

return (arr[I] % 2 == 0) || anyEven(arr,i+1);

Recursive Methods

• Write a recursive predicate method to determine if the

sequence of numbers in the given array is increasing.

public static boolean isIncreasing(int[] arr, int x, int i) {

if (i == arr.length) {

return true;

} else {

return (x < arr[i]) &&

(isIncreasing(arr,arr[i],i+1));

In this example, three input parameters are used in the recursive

case: the array arr, an integer x to "remember" the value of the

last element in the array, and an integer i to keep track of the

position of the current element in the array. The base case is

reached when i is equal to the size of the array.

The End