170 likes | 290 Views
CiS 260: App Dev I. Chapter 5: Methods and Classes. Introduction to Methods. A method (or ________) is a segment of code that performs a specific task. Advantages of modular program design: allows you to focus on a small part of the program many programmers can work on different methods
E N D
CiS 260: App Dev I Chapter 5: Methods and Classes
Introduction to Methods • A method (or ________) is a segment of code that performs a specific task. • Advantages of modular program design: • allows you to focus on a small part of the program • many programmers can work on different methods • encourages software reuse • improves the simplicity and readability of programs • Java provides ___________ methods in collections of classes called class __________. • Examples of predefined methods are println(), showInputDialog(), setText(), etc. • The programmer can create his own ___________ methods in classes he creates.
Predefined Methods • An algebraic function looks like f( x ) = 2x + 5 • f is the name of the function • 2x + 5 is the body of the function • x is the parameter of the function, any real number • if x = 2, we write f( 2 ) and 2 is the argument of f • f(2) = 2 * 2 + 5 = ___. • Java has a pow(x, y) method in the Math class • pow is the name of the method • x and y are the ____________ of the method, both of type double • For the arguments x=2 and y=3, Math.pow(2, 3) means 2 raised to the power 3, or ___ • You often need to use the import statement.
User-Defined Methods • Predefined methods are prewritten to perform common, basic tasks. • User-defined methods are ________ designed to perform very specialized tasks. • Two kinds of user-defined methods • value-returning (returns a result to the calling method) • void (doesn’t return a result, just executes)
Value-Returning Method • Every method has these five parts • name (such as pow or myCustomMethod) • parameter list (in parentheses) • ______ type of each parameter, like double • the data type of the returned value, like double • the program code executed by the method • The first four above constitute the method __________ and the last is called the ______. • The five components above constitute a method definition. • To use a method in a program, you must code a method _______.
Method Example • Suppose you wrote the following method public static double raiseToAPower (double base, double exponent) { double result = 1; for( int i = 1; i <= exponent; i++ ) result *= base; return result; } • public and static are modifiers, double is the return type, and raiseToAPower is the ______. • (double base, double exponent) is the parameter list and the code inside the {}’s is the ______.
Class With a User-Defined Method public class Power { public static void main( String[] args ) { double answer; answer = raiseToAPower( 2,3 ); // method ______ System.out.println(answer); // displays 8.0 } // end main public static double raiseToAPower (double base, double exponent) { double result = 1; for( int i = 1; i <= exponent; i++ ) result *= base; return result; // return this value to main } // end raiseToAPower } // end class
The Return Statement • The syntax of a return statement in a method is returnexpr; where expr is a variable, constant value, or ____________. • The data type of the value of expr must match the _______ type of the method. • When a return statement executes, the method terminates and control goes back to the ________. public static double larger( double x, double y ) { double max; if( x >= y ) max = x; else max = y; return max; }
Flow of Execution • The order of methods in a class doesn’t matter. • When a program executes, the first statement in the method ________ executes first. • When the last statement of a method executes, control is passed back to the point immediately following the method call. • For a value-returning method, the value that the method returns replaces the method call and execution follows immediately after the call. • A _________statement can be used in a void method to exit a method early. • To call a void method, use methodName();
Data Types and Parameters • For primitive data types, variables are passed from one method to another by ______ . • This means methods have their own copies of primitive data separate from each other. • For reference variables (objects or abstract data types) variables are passed by __________. • Therefore, a change in the value for a reference variable in one method, automatically changes it in any other method. • Remember that a variable of type String is a reference variable (points to a String _______).
Scope of an Identifier • The scope of an identifier is that part of the program in which it is accessible (________). • A ______ identifier is declared within a method or block and is visible only within that method or block. • When a counter variable is declared in a for loop, its scope is limited to the for loop.
Method Overloading • In Java, a class can contain several methods with the same name. • However, methods with the same name must have different _________________. • This is called method ____________. • This makes the naming of methods easier.
The class String • In Java, a string is not a variable, but an _____. • The following two statements are equivalent: • String name = “Lisa Johnson”; • name = new String( “Lisa Johnson” ); • nameis actually a reference variable that contains the address of the String ________. • A string contains ___ or more characters enclosed in double quotes. • The ________ of the first character in a string is 0, of the second character is 1, and so on.
Methods in the class String • The method substring() is a member of class String. • Using String name = “Lisa Johnson”; : • name.substring(0,4) yields _______ • name.substring(5,12) yields “Johnson” • name.indexOf(‘J’) yields ___ • name.charAt(4) yields ‘ ’ • name.equals(“Lisa Johnson”) yields true • name.equals(“Luke Johnson”) yields ______ • name.length() yields ____ • name.replace('i','e') yields “Lesa Johnson” • The String object name has access to the String methods using the ____ operator.
Formatting Numbers • You can format numbers in your program using complicated program logic (see p. 226) • Or you can use Java pre-defined methods: • NumberFormat decimal = NumberFormat.getNumberInstance(); • decimal.setMaximumFractionDigits(2); • String aDecimalStr = decimal.format(19.857); //19.86 • NumberFormat percent = NumberFormat.getPercentInstance(); • String aPercentStr = percent.format(.857); // 86% • NumberFormat currency = NumberFormat.getCurrencyInstance(); • String aCurrencStr = currency.format(19.95); //$19.95
The Calendar Class • Calendar today = Calendar.getInstance(); • int month = today.get( Calendar.MONTH ) + 1; // returns numeric month (1 for Jan, 2 for Feb, …) • Date todaysDate = today.getTime(); • System.out.print( todaysDate ); // prints date & time • Calendar dueDate = Calendar.getInstance(); • dueDate.set( 2007, 11, 31 ); // due date is Dec. 31
The GregorianCalendar Class • GregorianCalendar birthDate = new GregorianCalendar( 1953, 8, 10 ); // Sept. 10, 1953 • int dayOfWeek = birthDate.get( GregorianCalendar.DAY_OF_WEEK ); // returns, for example, Tuesday • Long birthTime = birthDate.getTimeInMillis(); // time in milliseconds • DateFormat longDate = DateFormat.getDateInstance( DateFormat.LONG ); • String birthDayStr = longDate.format( birthDate ); // “September 10, 1953”