CS2011 Introduction to Programming I Methods (I) Chengyu Sun California State University, Los Angeles
Example: Range Sum Find the sum of integers from 1 to 10, 20 to 37, and 35 to 49 Without method With method
Define A Method Method Header public static int sum( int begin, int end ) { int sum = 0; for( int i=begin; i <= end; ++i ) sum += i; return sum; } Method Body
Method Header A.K.A. method signature Method name A list of parameters ?? public static int sum ( int begin, int end ) Access modifier (in this course everything is public) Type of the returned value, a.k.a. return type
Parameters Function as variables in the method A.K.A. formal parameters Some methods don't have parameters, e.g. length() in String
Return Value A method may return a value: return <expression>; A return statement immediately terminates the execution of a method A method may return no value, in which case the return type in the method header should be void You can still use an empty return statement to end the method early Example: void splitName(String name)
Common Mistakes Related to Return Value Return value doesn't match return type Not returning value in some branches Try to return more than one value Unreachable code
Call A Method A.K.A. invoke a method For example: int n = sum( 20, 37 ); Values to assigned to the parameters (in order) Actual parameters, a.k.a. arguments Difference between calling a value returning method and a void method
Trace A Call Use Eclipse's debugger to trace the TestMax example
Why Use Methods … (a) encapsulate reusable logic Examples Range sum Math.sin(), Math.cos(), Math.random() …
… Why Use Methods … (b) encapsulate certain concept or operation (and it makes code more readable) Example: if( year%4 == 0 && year%100 != 0 || year%400 == 0 ) if( isLeapYear(year) )
… Why Use Methods (c) facilitate top-down programming – break down a big problem into smaller problems Create a method for solving the big problem, by calling methods that solve each smaller problem.
Example: Factorial n! = 1 * 2 * 3 … * (n-1) * n Terminate the method early when n < 0 Parameters and return value Return an error value Don't put too much in a method (also see the Range Sum example) Easier to test Maximize reusability
Example: Longest Palindrome Prefix/Suffix Method naming conventions Start with a lower-case letter Usually starts with a verb Usually starts with is for methods that return a boolean value