Download presentation
Presentation is loading. Please wait.
1
CS2011 Introduction to Programming I Methods (I)
Chengyu Sun California State University, Los Angeles
2
Example: Range Sum Find the sum of integers from 1 to 10, 20 to 37, and 35 to 49 Without method With method
3
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
4
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
5
Parameters Function as variables in the method
A.K.A. formal parameters Some methods don't have parameters, e.g. length() in String
6
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)
7
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
8
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
9
Trace A Call Use Eclipse's debugger to trace the TestMax example
10
Why Use Methods … (a) encapsulate reusable logic Examples Range sum
Math.sin(), Math.cos(), Math.random() …
11
… 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) )
12
… 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.
13
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
14
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.