61 Views

Download Presentation
## Chapter One: Methods, Arrays

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -

**Introducing Methods**• A method is a collection of statements that are grouped together to perform an operation.**Introducing Methods……**• Method signature is the combination of the method name and the parameter list. • The variables defined in the method header are known as formal parameters or simply parameter. • You need to declare a separate data type for each parameter. For instance, int num1,num2 should be replaced by int num1, int num2. • When a method is invoked, you pass a value to the parameter. This value is referred to asactual parameter or argument.**Introducing Methods……**A method may return a value. • ThereturnValueTypeis the data type of the value the method returns. • If the method does not return a value, the returnValueTypeis the keyword void. • For example, the returnValueTypein themainmethod is void.**Calling a method**• This program demonstrates calling a method max to return the largest of theintvalues**Calling a method…..**• public class TestMax { • /** Main method */ • public static void main(String[] args) { • int i = 5; • int j = 2; • int k = max(i, j); • System.out.println("The maximum between " + i + “ • and " + j + " is " + k); • } • /** Return the max between two numbers */ • public static int max(int num1, int num2) { • int result; • if (num1 > num2) • result = num1; • else • result = num2; • return result; • } • }**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**animation**Trace Method Invocation…. Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2**animation**Trace Method Invocation…. Trace Method Invocation result is now 5**animation**Trace Method Invocation…. Trace Method Invocation return result, which is 5**animation**Trace Method Invocation…. Trace Method Invocation return max(i, j) and assign the return value to k**animation**Trace Method Invocation…. Trace Method Invocation Execute the print statement**Reuse Methods from Other Classes**• One of the benefits of methods is for reuse. • The max method can be invoked from any(as it is declared public) class besides TestMax. • If you create a new class Test, you can invoke the max method using ClassName.methodName(…) (because it is declared static). Example: • Math.sqrt(900.0) • TestMax.max**Reuse Methods from Other Classes**• If it were not declared static the method is accessed using instance of the class, object. ClassName cn = new ClassName(…); cn.methodName(…);**animation**Trace Call Stack i is declared and initialized**animation**Trace Call Stack j is declared and initialized**animation**Trace Call Stack Declare k**animation**Trace Call Stack Invoke max(i, j)**Trace Call Stack**pass the values of i and j to num1 and num2**animation**Trace Call Stack pass the values of i and j to num1 and num2**animation**Trace Call Stack (num1 > num2) is true**animation**Trace Call Stack Assign num1 to result**animation**Trace Call Stack Return result and assign it to k**animation**Trace Call Stack Execute print statement**Passing Parameters**• There are two ways to pass a variable to the called function: Pass by value and pass by reference • Example (C++ code)**Passing Parameters**• Pass by value (how it works) • The contents of memory of i and j don't change • Pass by reference (how it works) • The contents of memory of i and j don't change Java is strictly pass by value**Overloading Methods**• Defining more than one methods with the same name but different parameter lists within one class. • The Java compiler determines which method is used based on the method signature.**Ambiguous Invocation**• Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. • This is referred to as ambiguous invocation. Example: max(1,2); • Ambiguous invocation is a compilation error.**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; } }**Benefits of Methods**• Write a method once and reuse it anywhere. • Avoids “reinventing a wheel” • Information hiding. Hide the implementation from the user. • You can think of the method body as a black box that contains the detailed implementation for the method. • Reduce complexity.**Methods defined in the Math Class**• Class constants: • PI • E (base of natural logarithm) • Class methods: • Trigonometric Methods • Exponent Methods • Rounding Methods • min, max, abs, and random Methods**Trigonometric Methods**• public static double sin(double redians) • public static double cos(double redians) • public static double tan(double redians) • public static double asin(double redians) • public static double acos(double redians) • public static double atan(double redians) • public static double toRadians(double degree) • public static double toDegrees(double degree)**Trigonometric Methods …….**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**• public static double exp(double a) Returns e raised to the power of a. • public static double log(double a) Returns the natural logarithm of a. (ln(x) = loge(x)) • public static double log10(double a) Returns the 10-based logarithm of a. • public static double pow(double a, double b) Returns a raised to the power of b. • public static double sqrt(double a) Returns the square root of a.**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**Rounding Methods**• public static double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. • public static double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. • public static 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. • public static int round(float x) Return (int)Math.floor(x+0.5). • public static long round(double x) Return (long)Math.floor(x+0.5).**Rounding Methods, example**Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns –2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 Math.rint(2.1) returns 2.0 Math.rint(2.0) returns 2.0 Math.rint(-2.0) returns –2.0 Math.rint(-2.1) returns -2.0 Math.rint(2.5) returns 2.0 Math.rint(-2.5) returns -2.0 Math.round(2.6f) returns 3 Math.round(2.0) returns 2 Math.round(-2.0f) returns -2 Math.round(-2.6) returns -3**min, max, and abs**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 • 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).**The random Method**• Generates a random double value greater than or equal to 0.0 and less than 1.0 (0.0 <= Math.random() < 1.0). Examples: In general,**Arrays**• In Java and other programming languages, there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. • This type of variable is called an array. • Array is a data structure that represents a collection of the same types of data, but it is often more useful to think of an array as a collection of variables of the same type.**Arrays…..**• Instead of declaring individual variables, such as number0,number1,….., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1],…., and numbers[99] to represent individual variables. • An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.**Declaring Arrays**• To use an array in a program, you must declare a variable to reference the array. • To declare an array, write the data type, followed by a set of square brackets[], followed by the identifier name. dataType[] arrayRefVar ; //preferred or dataTypearrayRefVar[]; Where: • dataTypespecifies the kind of values the array stores • the brackets []indicate this is an array • arrayRefVar is the handle to access the array**Creating Arrays**• Unlike declaration for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. Only a storage location for the reference to an array is created. • We can not assign a elements to an array unless it has already been created. • There are two different ways to create an array: • Using array literals • Using new operator