- Forward


An Introduction to Methods and Modularity
with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • Statement:
    • A smallest syntactically valid construct that conveys a complete command
  • Program:
    • A collection of statements to solve a particular problem in a particular imperative programming language
Motivation
Back SMYC Forward
  • Some Observations about Programs:
    • Understanding is inversely proportional to size
    • Reusability is inversely proportional to size
    • Small (and simple) components are easier to debug and fix than large (and complex) components
    • Portability is inversely proportional to size
  • The Implication:
    • Programs should be modular (i.e., organized into small components)
Achieving Modularity in Object-Oriented (and Other) Languages
Back SMYC Forward
  • Method (Function, Procedure, Subroutine):
    • Loosely, an encapsulation of a "standalone" computation/algorithm
  • Class (File):
    • Loosely, a collection of related methods (functions/procedures/subroutines) and information they use
  • Package (Directory, Folder):
    • Loosely, a collection of related classes (files)
Modular Programs in Java
Back SMYC Forward
  • All Programs:
    • Every program must consist of at least one class (called the "main" class)
    • The "main" class of all applications (one kind of Java program) must have a method that is the "entry point of the program" with the signature
      public static void main(String[] identifier)
      that is passed the command line arguments when the program is executed. Note: The formal parameter can have any identifier (though args is common) but must be a String[].
  • Well-Designed Programs:
    • Consist of classes containing methods that are closely related to each other (i.e., are cohesive)
    • Use small methods, each of which serves a well-defined and easily-understood purpose
Declaring Classes in Java
Back SMYC Forward
  • Classes:
    • accessibility class name { [attributes]... [methods]... }
  • File/Class Names:
    • The name of the file containing a class must be exactly the same as the name of the class (with .java appended)
    • A common style requirement is that class names must start with an uppercase letter
  • For Now:
    • All of your classes must be public (more on this in CS159)
Declaring Methods in Java
Back SMYC Forward
  • Syntax:
    • accessibility [static] type name([type formal_parameter], ...)
  • Style:
    • A common style requirement is that method names must start with a lowercase letter
  • For Now:
    • All of your methods must be static indicating that the method "belongs to" the class (more on this later)
  • Examples:
    • public static double circleArea(double diameter)
    • private static boolean isPrime(int n)
Invoking/Calling Methods in Java
Back SMYC Forward
  • Syntax:
    • class|object.name([actual_parameter], ...)
  • For Now:
    • Since all methods "belong to" a class, they must all be invoked using the class name (again, more on this later)
Invoking/Calling Methods in Java (cont.)
Back SMYC Forward
  • A Subtlety:
    • The class (or object) that the method "belongs to" can sometimes be inferred and, hence, can sometimes be omitted (which can be confusing to beginning programmers)
  • Examples:
    • From a different class: Geometry.circleArea(5.0)
    • From the same class: circleArea(5.0)
Invoking/Calling Methods in Java (cont.)
Back SMYC Forward
  • Another Subtlety:
    • When executing an application (e.g., from the command line or inside of an IDE) the name of the entry point is omitted (because it must be main())
  • Example:
    • From the command line: java GradeCalculator
More on Parameters (a.k.a. Arguments)
Back SMYC Forward
  • Definition:
    • A named space that allows information to be passed to a method
  • Types:
    • Formal - the named parameters in the declaration of a method (that are said to specify the interface to the method)
    • Actual - the parameters (which can be variables or literals) that are passed to a method when it is invoked
  • Associating Actual and Formal Parameters:
    • In Java, the actual parameters are associated with the formal parameters based on their position
      parameters_formal-and-actual
More on Parameters (cont.)
Back SMYC Forward
  • An Important Detail of Java:
    • A copy of the actual parameter is passed
  • An Implication:
    • The value of the actual parameter can't be changed in a method (though the value of the copy can be)
  • Be Careful:
    • Remember that Java has reference types as well as atomic/primitive/fundamental types and a copy of an address can be used in ways that are very similar to the original address
More on the Returned Value/Result
Back SMYC Forward
  • Definition:
    • The result of executing the statements in a method (a.k.a. evaluating the method) that is "returned to" the caller
  • Number of Returned Values:
    • In Java, a method can return zero values (in which case it is said to be void) or one value
More on the Returned Value/Result (cont.)
Back SMYC Forward
  • Typed Methods:
    • The returned value has a type and the method is often said to be of that type
    • In the calling statement, the method evaluates to the returned value (if there is one), making it an expression
  • void Methods:
    • The method changes the state of the system in some useful way (e.g., displays output, changes a global variable)
A Method with One Parameter
Back SMYC Forward
javaexamples/basics/FunctionExamples.java (Fragment: circleArea)
 
A Method with Multiple Parameters
Back SMYC Forward
javaexamples/basics/FunctionExamples.java (Fragment: fuelPerformance)
 
An Example of Using a Method
Back SMYC Forward
  • A Simple Class with One Method:
    • public class Geometry { public static double rectangleArea(double width, double height) { return (width * height); } }
  • Invoking/Calling this Method from Another Class:
    • area = Geometry.rectangleArea(300.0, 10.0);
  • Invoking/Calling this Method from the Geometry Class:
    • area = rectangleArea(10.0, 10.0);
An Example of Using a Method (cont.)
Back SMYC Forward

Review Questions

  • What are the formal and actual parameters?
  • What is the correspondence between the formal and actual parameters?
  • Can the actual parameters be variables (not literals)?
  • If they are, do the identifiers have to be the same? Can they be?
A Visualization of a Method Call
Back SMYC Forward
railroad_method
A Visualization of a Method Call and Return
Back SMYC Forward
railroad_method_call-and-return
Some Important Methods in the Java API
Back SMYC Forward
  • In the Math Class:
    • double abs(double d), int abs(int i), ...
    • double sin(double d), ...
    • double log(double d), double log10(double d), ...
    • double min(double d, double e), double max(double d, double e), ...
    • double pow(double d, double p)
    • double sqrt(double d)
  • In the Integer Class:
    • int parseInt(String s)
  • In the Double Class:
    • double parseDouble(String s)
  • In the Array Class:
    • int getLength(double[] a), ...
Class Constants in Java
Back SMYC Forward
  • The Need for Class Constants:
    • We frequently need to use the same constant in multiple methods (e.g., \(\pi\) is used in the calculation of the circumference and the area of a circle)
  • An Observation:
    • Such constants can't be declared within a method (because they won't be accessible outside of that method)
  • The Solution:
    • Declare and initialize them outside of any method (adding the static modifier)
    • If they are declared to be public they can even be used outside of the class (e.g., Math.PI)
    • If they are declared to be final they can't be changed
Class Constants in Java (cont.)
Back SMYC Forward
  • Syntax: Click here for information.
    • accessibility static final type identifier = value;
  • Examples:
    • public static final boolean CORRECT = true;
    • public static final double BUDGET = 100000.0;
    • private static final int CAPACITY = 5;
  • When Are These Statements Executed?
    • Once, when the class is loaded
Some Important Class Constants in the Java API
Back SMYC Forward
  • In the Math Class:
    • E (base of the natural log)
    • PI
  • In the Integer Class:
    • MIN_VALUE
    • MAX_VALUE
  • In the Double Class:
    • NEGATIVE_INFINITY
    • POSITIVE_INFINITY
    • MIN_VALUE
    • MAX_VALUE
Putting It All Together - A Utility Class
Back SMYC Forward
javaexamples/basics/Geometry.java
 
Putting It All Together - A Main Class
Back SMYC Forward
javaexamples/basics/AreaCalculator.java
 

Make sure you can trace the execution of the above program assuming it is executed with a single command-line parameter (e.g., the String 10).

An Introduction to Scope
Back SMYC Forward
  • The Concept:
    • The region of a program within which an entity can be referred to by name
  • Some Common Types:
    Block Within a block of code (i.e., between a { and })
    Method Within a method (which includes both formal parameters and variables declared within the method)
    Class Everywhere within a class
    Global Everywhere
An Introduction to Scope (cont.)
Back SMYC Forward
javaexamples/basics/FunctionExamples.java (Fragment: fuelPerformance)
 
javaexamples/basics/FunctionExamples.java (Fragment: fuelUseReporter)
 
An Introduction to Scope (cont.)
Back SMYC Forward
javaexamples/basics/FunctionExamples.java (Fragment: noParameters)
 
javaexamples/basics/FunctionExamples.java (Fragment: scope1)
 
An Introduction to Scope (cont.)
Back SMYC Forward
javaexamples/basics/FunctionExamples.java (Fragment: actualParameters)
 
javaexamples/basics/FunctionExamples.java (Fragment: scope2)
 
There's Always More to Learn
Back -