CIS 3020 Part 4

From In The Wings
Jump to navigation Jump to search

Variables

Variable: An identifier that can be given a value

  • Associated with primitive types

Reference Variable: A variable whose value is a reference

  • Associated with instances of a class
  • Most programmers refer to both as variables
  • There is a fundamental difference in how they are used internally

String Methods

Method Return Value Arguments Definition
toUpperCase Reference to String Object None Shifts all alpha-characters to uppercase
toLowerCase Reference to String Object None Shifts all alpha-characters to lowercase
length int None Returns number of characters in string
trim Reference to String Object None Removes white space from end of string object
concat Reference to String Object Reference to String Object Concatenates string object in argument to original string object
substring Reference to String Object int Returns substring of original string from position given to end
substring Reference to String Object int,int Returns substring of original string from position given to second position given

Bound Variables

Given two methods:

public int test (int x) {
  body1
}
public int square (int x) {
  body2
}

are the two x's the same?

No! These are formal parameters of their respective methods. The method definitions bind them.

  • A variable is said to be bound in an expression if the meaning of the expression is unchanged when the variable is consistently renamed throughout the expression.
  • In other words, replace x with some other name like p throughout the its entire method and the definition of the method should remain the same.
  • Also referred to as a "local variable".

Scope (of a name)

That portion of a program in which there is a binding for a particular name

Free name

  • A variable or method name is said to be free in an expression if it is not bound
public boolean goodEnough(double guess, double x) {
  return (abs(square(guess) -x) < 0.001);
}
  • Bound variables: goodEnough, guess, x
  • Free variables: abs, square

Linear Recursion

  • Suppose I would like to know how many students are in row 2
  • Rather than counting each student, I will let them count themselves
  • Each student will:
    • Give a count of 1 if no one is to their left
    • Will ask the person to their left for a count then will give an answer one larger than that value
  • The factorial function is the prototype example of linear recursion:
n! = n * (n-1) * (n-2) * ... * 3 * 2 * 1
  • Note that this is the same as:
n * (n-1) * (n-2) * ... * 3 * 2 * 1 = n * (n-1)!

i.e.

n! = n * (n-1)!