710 likes | 892 Views
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
E N D
SD1420Unit 3 – Chapters 5 and 6 Methods and Single-Dimensional Arrays
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
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.
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).
Trace Call Stack i is declared and initialized
Trace Call Stack j is declared and initialized
Trace Call Stack Declare k
Trace Call Stack Invoke max(i, j)
Trace Call Stack pass the values of i and j to num1 and num2
Trace Call Stack Declare result
Trace Call Stack (num1 > num2) is true
Trace Call Stack Assign num1 to result
Trace Call Stack Return result and assign it to k
Trace Call Stack Execute print statement
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”);
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; } }
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.
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.
Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.
Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.
The Math Class • Class constants: • PI • E • Class methods: • Trigonometric Methods • Exponent Methods • Rounding Methods • min, max, abs, and random Methods
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
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.
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).
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
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:
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'); } }
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Declaring Array Variables • datatype[] arrayRefVar; Example: double[] myList; • datatype arrayRefVar[]; // This style is allowed, but not preferred Example: double myList[];
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.
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];
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
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.
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];
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.
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;
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};
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)
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.
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 ;
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];
The arraycopy Utility arraycopy(sourceArray, src_pos, targetArray, tar_pos, length); Example: System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);