Methods - PowerPoint PPT Presentation

About This Presentation
Title:

Methods

Description:

Methods A class declaration may contain one or more method declaration. A method is a group of statements that are given a name. Each method will be associated with a ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 21
Provided by: Ilya88
Category:

less

Transcript and Presenter's Notes

Title: Methods


1
Methods
  • A class declaration may contain one or more
    method declaration.
  • A method is a group of statements that are given
    a name.
  • Each method will be associated with a particular
    class (or with an instance of that class).
  • We may define methods and invoke them with
    different parameters. When its parameters are
    different, their behavior will be different.
  • A method declaration specifies the code that will
    be executed when the method is invoked (called)
  • When a method is invoked, the flow of control
    jumps to the method and executes its code
  • When complete, the flow returns to the place
    where the method was called and continues

2
Method Definition
  • All methods follow the same syntax when they are
    defined
  • modifiers return-type method-name (
    formal-parameter-list )
  • statements
  • return-type indicates the type of the value
    returned from this method.
  • method-name is the name of this method (an
    identifier),
  • formal-parameter-list indicates
  • A comma separated list of zero or more type
    name pairs.
  • how many parameters will be taken by this method
  • the names of the formal parameters (how do we use
    them in the inside of this method)
  • the data types of these parameters
  • statements are the executable statements (and
    declarations for local variables) of this method.
    These statements will be executed when this
    method is invoked.

3
Method Definition -- Example
  • return-type method-name formal-parameter-list
  • int thirdPower(int num)
  • int cube local variable declaration
  • cube numnumnum
  • return cube return statement

Local variables are created each time the method
is called, and they are destroyed when it
finishes executing
The return expression must be consistent with the
return type
4
Return-Type and Return Statement
  • The return type can be any data type (a primitive
    data type or an object data type) or void.
  • A return statement will be in the following form
  • return expression where the type of the
    expression must be the same as (assignment
    compatible) the return type of that method.
  • If the return type of a method is different from
    void, that method must contain at least one
    return statement.
  • When a return statement is executed in that
    method , we exit from that method by returning
    the value of the expression in that return
    statement.
  • Normally, method calls for these methods are
    parts of expressions.
  • If the return type of a method is void, that
    method does not need to have a return statement.
  • In this case, when the last statement in that
    method is executed, we return from that method.
    (Or, it may contain a return statement without an
    expression return )
  • Normally, a method call for the method with void
    return type is a statement

5
Parameters
  • A method accept zero or more parameters
  • Each parameter in the parameter list is specified
    by its type and name.
  • The parameters in the method definition are
    called formal parameters.
  • The values passed to a method when it is invoked
    are called actual parameters.
  • The first actual parameter corresponds to the
    first formal parameter, the second actual
    parameter to second formal parameter, and so on..
  • The type of the actual parameter must be
    assignment compatible with the corresponding
    formal parameter.

6
Modifiers Visibility
  • Access (Visibility) Modifiers
  • public accessible in all classes
  • protected accessible in the classes in the
    package or inherited classes
  • private accessible only in current class
  • no access modifier means, the method is
    accessible in the classes in the package
  • Packages are collections of classes
  • Classes are collections of methods ( variables)
  • Methods are collections of statements

7
Static or Instance Method
  • If a method is declared with static keyword, it
    is a static method Otherwise it is an instance
    method.
  • A static method is associated with a class, and
    it has only one copy. It can be invoked with the
    name of the class.
  • An instance method is associated with an object
    of a class, and it can be invoked with an object
    of the class.
  • An instance method is always executed in the
    context of an object.

8
Invoking A Static Method
  • In the same class
  • method-name ( actual-parameters )
  • Example f(4,5)
  • In a different class
  • Class-name . method-name ( actual-parameters )
  • Example y Math.sin(x)

9
Invoking An Instance Method
  • In the same class
  • method-name ( actual-parameters )
  • Example f(4,5)
  • In a different class
  • anobject . method-name ( actual-parameters )
  • Example scan.nextLine()

10
Definition Use of Static Methods
// header // Author, date public class ClassName
public static void myMethod1( String s)
System.out.println( s) private static int
myMethod2( int i) return i 2
1 public static void main( String args)
myMethod1( Hello) int j myMethod2(
5) System.out.println( j)
Methods declared in class (but outside main)
Return statement indicates what value will be
considered the result of the method (function)
Use in main or other method
11
Example
  • Method to find hypotenuse of triangle

public static double hypotenuse( double side1,
double side2) double side3 side3
Math.sqrt( side1 side1 side2
side2) return side3
Any variables, like side3, that are not
parameters should be defined locally.
Actual formal parameters are matched one-to-one
in sequence,e.g side1 3, side2 4
  • Use

double z hypotenuse( 3, 4)
12
Parameter passing (1)
10
13
13
a 5 b 3 c myMethod( a, b) System.out.prin
tln( c)
z 2 x return z y
13
Parameter passing (2)
6
11
11
a 5 b 3 c myMethod( b, a) System.out.prin
tln( c)
z 2 x return z y
14
Method exercises
  • isLessThan( x, y) - return boolean!
  • x to the power y
  • Determine if an int value isPrime or not.
  • isPalindrome
  • Convert binary string to int

15
isLessThan
  • // isLessThan returns true if xlty otherwise it
    return false
  • public static boolean isLessThan(int x, int y)
  • return (xlty)

16
x to the power y
  • public static double nthpower(double x, int n)
  • double result 1.0
  • int i
  • for (i1 iltn i)
  • result result x
  • return result

17
Combination-Permutation Example
  • import java.util.Scanner
  • public class CombPerm
  • public static void main(String args)
  • int n,r,combVal,permVal
  • // Create a Scanner object
  • Scanner scan new Scanner(System.in)
  • System.out.print("An Integer Number (N)gt
    ")
  • n scan.nextInt()
  • System.out.print("An Integer Number (R)gt
    ")
  • r scan.nextInt()
  • // Calculate Combination and permutation
  • combVal comb(n,r)
  • permVal perm(n,r)
  • System.out.println("C(n,r) " combVal)

18
Combination-Permutation Example (cont.)
  • // C(n,r) n! / (r! (n-r)!)
  • static int comb(int n, int r)
  • return fact(n)/(fact(r)fact(n-r))
  • // P(n,r) n! / (n-r)!
  • static int perm(int n, int r)
  • return fact(n)/fact(n-r)
  • // Factorial
  • static int fact(int n)
  • int i,val
  • val 1 i1
  • while (iltn)
  • val vali
  • i i 1

19
Palindrome
  • import java.util.Scanner
  • public class Palindrome
  • public static void main(String args)
  • String s
  • // Create a Scanner object
  • Scanner scan new Scanner(System.in)
  • System.out.print("A stringgt ")
  • s scan.nextLine()
  • // Check s is a palindrome or not.
  • if (isPalindrome(s))
  • System.out.println(s " is
    PALINDROME.")
  • else
  • System.out.println(s " is NOT
    PALINDROME.")

20
Palindrome (cont.)
  • public static boolean isPalindrome(String s)
  • boolean flag true
  • int i, j
  • i 0
  • j s.length()-1
  • while (flag iltj)
  • if (s.charAt(i) ! s.charAt(j))
  • flag false
  • else
  • i
  • j--
  • return flag
Write a Comment
User Comments (0)
About PowerShow.com