1 / 86

Java Programing

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.

mpino
Download Presentation

Java Programing

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programing Methods

  2. Defining Methods A method is a collection of statements that are grouped together to perform an operation.

  3. Defining Methods A method is a collection of statements that are grouped together to perform an operation.

  4. Method Signature Method signature is the combination of the method name and the parameter list.

  5. Formal Parameters The variables defined in the method header are known as formal parameters.

  6. Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.

  7. 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.

  8. Calling Methods Testing the max method This program demonstrates calling a method max to return the largest of the int values

  9. Calling Methods, cont.

  10. Trace Method Invocation i is now 5

  11. Trace Method Invocation j is now 2

  12. Trace Method Invocation invoke max(i, j)

  13. Trace Method Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

  14. Trace Method Invocation declare variable result

  15. Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2

  16. Trace Method Invocation result is now 5

  17. Trace Method Invocation return result, which is 5

  18. Trace Method Invocation return max(i, j) and assign the return value to k

  19. Trace Method Invocation Execute the print statement

  20. 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; }

  21. 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); }…,,,

  22. 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; }

  23. 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)

  24. 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.

  25. 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).

  26. 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”); } }

  27. Call Stacks

  28. Method Overloading Method overloading • Several methods of the same name • Different parameter set for each method • Number of parameters • Parameter types

  29. 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);

  30. 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

  31. 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; }

  32. 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

  33. 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)

  34. 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”);

  35. 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.

  36. Pass by Value…

  37. 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

  38. 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]

  39. 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; }

  40. 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]

  41. 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]

  42. 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.

  43. 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

  44. 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

  45. Find the output int i = 1, j = 1, val; while (i < 25){ System.out.println(j + " "); val = i + j; j = i; i = val; }

  46. 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"); • }

  47. 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

  48. 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.

  49. Array declaration type[] name = new type[length]; • Example: int[] numbers = new int[10];

  50. 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.

More Related