1 / 71

SD1420 Unit 3 – Chapters 5 and 6

SD1420 Unit 3 – Chapters 5 and 6. Methods and Single-Dimensional Arrays. Objectives. Upon completion of this unit, you will be able to do the following: D efine methods with formal parameters Invoke methods with actual parameters Define methods with a return value

paco
Download Presentation

SD1420 Unit 3 – Chapters 5 and 6

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. SD1420Unit 3 – Chapters 5 and 6 Methods and Single-Dimensional Arrays

  2. Objectives Upon completion of this unit, you will be able to do the following: • Define methods with formal parameters • Invoke methods with actual parameters • Define methods with a return value • Define methods without a return value • Develop reusable code that is modular, easy to read, easy to debug, and easy to maintain • Write a method that converts decimals to hexadecimals • Declare array reference variables and create arrays • Declare, create, and initialize an array using an array initializer • Copy contents from one array to another • Search elements using the linear or binary search algorithm • Sort an array using the selection sort approach

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

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

  10. Call Stacks

  11. Trace Call Stack i is declared and initialized

  12. Trace Call Stack j is declared and initialized

  13. Trace Call Stack Declare k

  14. Trace Call Stack Invoke max(i, j)

  15. Trace Call Stack pass the values of i and j to num1 and num2

  16. Trace Call Stack Declare result

  17. Trace Call Stack (num1 > num2) is true

  18. Trace Call Stack Assign num1 to result

  19. Trace Call Stack Return result and assign it to k

  20. Trace Call Stack Execute print statement

  21. Passing Parameters public static void nPrintln(String message, int n) { for (int i = 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”);

  22. Ambiguous Invocation public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } }

  23. Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

  24. Scope of Local Variables, cont. A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable.

  25. Scope of Local Variables, cont.

  26. Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.

  27. Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.

  28. The Math Class • Class constants: • PI • E • Class methods: • Trigonometric Methods • Exponent Methods • Rounding Methods • min, max, abs, and random Methods

  29. Trigonometric Methods • sin(double a) • cos(double a) • tan(double a) • acos(double a) • asin(double a) • atan(double a) Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0

  30. Exponent Methods Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 • exp(double a) Returns e raised to the power of a. • log(double a) Returns the natural logarithm of a. • log10(double a) Returns the 10-based 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.

  31. Rounding Methods • double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. • double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. • double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. • int round(float x) Return (int)Math.floor(x+0.5). • long round(double x) Return (long)Math.floor(x+0.5).

  32. min, max, and abs • 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 valuein the range [0.0, 1.0). Examples: Math.max(2, 3) returns 3 Math.max(2.5, 3) returns 3.0 Math.min(2.5, 3.6) returns 2.5 Math.abs(-2) returns 2 Math.abs(-2.1) returns 2.1

  33. The random Method Generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0). Examples: In general:

  34. The RandomCharacter Class // RandomCharacter.java: Generate random characters public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) { return (char)(ch1 + Math.random() * (ch2 - ch1 + 1)); } /** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z'); } /** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z'); } /** Generate a random digit character */ public static char getRandomDigitCharacter() { return getRandomCharacter('0', '9'); } /** Generate a random character */ public static char getRandomCharacter() { return getRandomCharacter('\u0000', '\uFFFF'); } }

  35. Introducing Arrays Array is a data structure that represents a collection of the same types of data.

  36. Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];

  37. Creating Arrays arrayRefVar = new datatype[arraySize]; Example: myList = new double[10]; myList[0] references the first element in the array. myList[9] references the last element in the array.

  38. Declaring and Creating in One Step • datatype[] arrayRefVar = new datatype[arraySize]; double[] myList = new double[10]; • datatype arrayRefVar[] = new datatype[arraySize]; double myList[] = new double[10];

  39. The Length of an Array Once an array is created, its size is fixed. It cannot be changed. You can find its size using: arrayRefVar.length For example, myList.length returns 10

  40. Default Values When an array is created, its elements are assigned the default value of: 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.

  41. Indexed Variables The array elements are accessed through the index. The array indices are 0-based, i.e., it starts from 0 to arrayRefVar.length-1. Each element in the array is represented using the following syntax, known as an indexed variable: arrayRefVar[index];

  42. Array Initializers • Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.

  43. Declaring, creating, initializing Using the Shorthand Notation double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double[] myList = new double[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;

  44. CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double[] myList; myList = {1.9, 2.9, 3.4, 3.5};

  45. Processing Arrays See the examples in the text: • (Initializing arrays with input values) • (Initializing arrays with random values) • (Printing arrays) • (Summing all elements) • (Finding the largest element) • (Finding the smallest index of the largest element) • (Random shuffling) • (Shifting elements)

  46. Shifting Elements

  47. Enhanced for Loop (for-each loop) JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable. For example, the following code displays all elements in the array myList: for (double value: myList) System.out.println(value); In general, the syntax is for (elementType value: arrayRefVar) { // Process the value } You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.

  48. Copying Arrays Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows: list2 = lists ;

  49. Copying Arrays Using a loop: int[] sourceArray = {2, 3, 1, 5, 10}; int[] targetArray = new int[sourceArray.length]; for (int i = 0; i < sourceArrays.length; i++) targetArray[i] = sourceArray[i];

  50. The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

More Related