Download presentation
Presentation is loading. Please wait.
Published byGyles Foster Modified over 9 years ago
1
TOPIC 6 Methods F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters F Pass by Value F Overloading Methods F Method Abstraction The Math Class
2
Creating A Method
3
Declaring Methods public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; }
4
Calling Methods F Two ways to call/invoke: (1)Method returns a value - call to method usually treated as a value - e.g. int larger = max(3, 4); System.out.println(max(3, 4)); (2)Method returns void - call to method must be a statement - e.g. System.out.println(“Welcome”);
5
Calling Methods F How is control passed back to the calling method?
6
public class TestMax { public static void main(String [ ] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println(“Maximum between “ + i + “ and “ + j + “ is “ + k); } public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; }
7
Passing Parameters F Formal parameters F Actual parameters F Parameter order association –Actual parameters must match the formal parameters in type, order and number. F Pass by Value -Copy of the value of the actual parameter is passed to the method. -Actual value of parameter outside method is not affected, regardless of any changes made to the formal parameter inside the method.
8
Overloading Methods double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } Methods have the same name i.e. max, but different parameters. F Method signature –Method name with the parameter profiles. –Java runtime system determines which method to used based on the message signature.
9
The Math Class F Class constants: –PI –E F Class methods: –Trigonometric Methods –Exponent Methods –Miscellaneous
10
Exponent Methods exp(double a) Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a.
11
Miscellaneous Methods max(a, b) and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.