880 likes | 928 Views
Java Programing. Methods. Defining Methods. A method is a collection of statements that are grouped together to perform an operation. Defining Methods. A method is a collection of statements that are grouped together to perform an operation. Method Signature.
E N D
Java Programing Methods
Defining Methods A method is a collection of statements that are grouped together to perform an operation.
Defining Methods A method is a collection of statements that are grouped together to perform an operation.
Method Signature Method signature is the combination of the method name and the parameter list.
Formal Parameters The variables defined in the method header are known as formal parameters.
Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
Return Value Type • A method may return a value. • The returnValueType is the data type of the value the method returns. • If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.
Calling Methods Testing the max method This program demonstrates calling a method max to return the largest of the int values
Trace Method Invocation i is now 5
Trace Method Invocation j is now 2
Trace Method Invocation invoke max(i, j)
Trace Method Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2
Trace Method Invocation declare variable result
Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2
Trace Method Invocation result is now 5
Trace Method Invocation return result, which is 5
Trace Method Invocation return max(i, j) and assign the return value to k
Trace Method Invocation Execute the print statement
Returning a value public static typename(parameters) { statements; ... return expression; } • Example: // Returns the slope of the line between the given points. public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; return dy / dx; }
Return examples // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC; } // Computes triangle hypotenuse length given its side lengths. public static double hypotenuse(int a, int b) { double c = Math.sqrt(a * a + b * b); return c; } • You can shorten the examples by returning an expression: public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32); }…,,,
Fixing the common error • Instead, returning sends the variable's value back. • The returned value must be stored into a variable or used in an expression to be useful to the caller. public static void main(String[] args) { double s = slope(0, 0, 6, 3); System.out.println("The slope is " + s); } public static double slope(int x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; }
System.out.printf an advanced command for printing formatted text System.out.printf("format string", parameters); • A format string contains placeholders to insert parameters into it: • %d an integer • %f a real number • %s a string • Example: int x = 3; int y = 2; System.out.printf("(%d, %d)\n", x, y); // (3, 2)
CAUTION A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value. To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.
Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).
Reuse Methods from Other Classes • The easiest way to call a method is to declare it as publicstatic • In the same class call the method using its name • In another class , call the method as classname.methodName class A { public static void m1() { System.out.println(“Hello 2”); } public static void main (String [ ] arg ) { System.out.println(“Hello 1”); m1(); System.out.println(“Hello 3”); } } class B { public static void main (String [ ] arg ) { System.out.println(“Hello 1”); A.m1(); System.out.println(“Hello 3”); } }
Method Overloading Method overloading • Several methods of the same name • Different parameter set for each method • Number of parameters • Parameter types
Method Overloading • A class may define multiple methods with the same name---this is called method overloading • usually perform the same task on different data types • Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … • The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);
Version 1 Version 2 double tryMe (int x, double y) { return x * y; } double tryMe (int x) { return x + .375; } Invocation result = tryMe (25, 4.32) Method Overloading
More Examples double tryMe ( int x ) { return x + 5; } Which tryMe will be called? tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); double tryMe ( double x ) { return x * .375; } double tryMe (double x, int y) { return x + y; }
Recursion Recursive method • Calls itself (directly or indirectly) through another method • Method knows how to solve only a base case • Method divides problem • Base case • Simpler problem • Method now divides simpler problem until solvable • Recursive call • Recursive step
Example Using Recursion: The Fibonacci Series • Fibonacci series • Each number in the series is sum of two previous numbers • e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…fibonacci(0) = 0 fibonacci(1) = 1fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 ) • fibonacci(0) and fibonacci(1) are base cases • Golden ratio (golden mean)
Passing Parameters public static void nPrintln(String message, int n) { for (inti = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using • nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using • nPrintln(“Computer Science”, 15); What is the output? Can you invoke the method using • nPrintln(15, “Computer Science”);
Pass by Value • When you invoke a method with an argument, the value of the argument is passed to the parameter. • This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method.
Array parameter example public static void main(String[] args) { int[] iq = {126, 84, 149, 167, 95}; double avg = average(iq); System.out.println("Average = " + avg); } public static double average(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return (double) sum / array.length; } Output: Average = 124.2
Arrays passed by reference iq a • Arrays are objects. • When passed as parameters, they are passed by reference.(Changes made in the method are also seen by the caller.) • Example: public static void main(String[] args) { int[] iq = {126, 167, 95}; doubleAll(iq); System.out.println(Arrays.toString(iq)); } public static void doubleAll(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = a[i] * 2; } } • Output: [252, 334, 190]
Arrays as return (declaring) public static type[]methodName(parameters) { • Example: public static int[] countDigits(int n) { int[] counts = new int[10]; while (n > 0) { int digit = n % 10; n = n / 10; counts[digit]++; } return counts; }
Arrays as return (calling) type[] name =methodName(parameters); • Example: public static void main(String[] args) { int[] tally = countDigits(229231007); System.out.println(Arrays.toString(tally)); } Output: [2, 1, 3, 1, 0, 0, 0, 1, 0, 1]
Array param/return question • Modify our previous Sections program to use static methods that use arrays as parameters and returns. Sections attended: [9, 6, 7, 4, 3] Student scores: [20, 18, 20, 12, 9] Student grades: [100.0, 90.0, 100.0, 60.0, 45.0] Sections attended: [6, 7, 5, 6, 4] Student scores: [18, 20, 15, 18, 12] Student grades: [90.0, 100.0, 75.0, 90.0, 60.0] Sections attended: [5, 6, 5, 7, 6] Student scores: [15, 18, 15, 20, 18] Student grades: [75.0, 90.0, 75.0, 100.0, 90.0]
Example • Create circle class that consists of the circle radius with methods to initialize the radius, calculate the circumference of the circle, and calculate the area of the circle.
Example • Create a class Time that contains data members, hour, minute, second to store the time value, and sets hour, minute, second to zero, provide three methods for converting time to ( 24 hour ) and another one for converting time to (12 hour) and a function that sets the time to a certain value specified by three parameters
Example • Write a 12-hour clock program that declares a clock class to store hours, minutes, seconds, A.M. and P.M. provide methods to perform the following tasks: • Set hours, minutes, seconds to 00:00:00 by default • Initialize hours, minutes, seconds, A.M. and P.M. from user entries • Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12-hour clock value of AM or PM • Display the time in hours:minutes:seconds AM / PM format
Find the output int i = 1, j = 1, val; while (i < 25){ System.out.println(j + " "); val = i + j; j = i; i = val; }
Find the output • intval; • for (val = -5; val <= 5; val++) • { • switch (val) • { • case 0: • System.out.println("India"); • break; • } • if (val > 0) • System.out.println("B"); • else if (val < 0) • System.out.println("X"); • }
Program • Create class account to save personal account for a bank with interest. • The class has account# and balance data • The class has operations: • deposit, withdraw, interest_earned {2% interest will be credited to account at end of each month if balance exceeds $10,000} and display_data
Arrays element 0 element 4 element 9 • array: object that stores many values of the same type. • element: One value in an array. • index: A 0-based integer to access an element from an array.
Array declaration type[] name = new type[length]; • Example: int[] numbers = new int[10];
Array declaration, cont. • The length can be any integer expression. int x = 2 * 3 + 1; int[] data = new int[x % 5 + 2]; • Each element initially gets a "zero-equivalent" value.