- Forward


An Introduction to Using Functions/Methods
with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Overview
Back SMYC Forward
  • Functions in Mathematics:
    • A mapping between two sets (called the domain and range)
  • The Role of Functions in Computing:
    • Determine the output based on one or more inputs
    • Perform some operation based on zero or more inputs
Examples
Back SMYC Forward
  • Using a Trigonometric Function:
    • \(o = \tan(\alpha) \cdot a\)
  • Using the Square Root:
    • \(c = \sqrt{a^2 + b^2}\)
    • \(l = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}\)
What You Need to Know to Use a Function/Method in Java
Back SMYC Forward
  • The class/object that has the function/method
  • The name (and purpose) of the function/method
  • The parameters (a.k.a., arguments) and their types (if any)
  • The return type (if any)
Examples
Back SMYC Forward
  • The Statement:
    • opposite = Math.tan(alpha) * adjacent;
  • What Was Needed:
    • The function belongs to the Math class
    • The name of the function is tan
    • The function has one double-valued parameter
    • The function returns a double
  • Where You Find What Was Needed:
    • Documentation for Math.tan(double)
Examples (cont.)
Back SMYC Forward
  • The Statement:
    • c = Math.hypot(a, b);
  • What Was Needed:
    • The function belongs to the Math class
    • The name of the function is hypot
    • The function has two double-valued parameters
    • The function returns a double
  • Where You Find What Was Needed:
    • Documentation for Math.hypot(double, double)
Examples (cont.)
Back SMYC Forward
  • The Statement:
    • length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  • What Was Needed:
    • The function belongs to the Math class
    • The name of the function is sqrt
    • The function has one double-valued parameter
    • The function returns a double
  • Where You Find What Was Needed:
    • Documentation for Math.sqrt(double)
void Functions/Methods
Back SMYC Forward
  • What They Are:
    • Functions/methods that don't return anything
  • Their Role:
    • They do something (e.g., change something) but don't need to return anything
  • An Example:
    • Printing/displaying something on the screen
An Example of a void Function/Method
Back SMYC Forward
  • The Statement:
    • System.out.println("Start Wearing Purple");
  • What Was Needed:
    • The method belongs to the out object in the System class
    • The name of the method is println
    • The method has one String parameter
    • The method does not return anything (i.e., is void)
There's Always More to Learn
Back -