Java Methods Explained PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an overview of methods in Java programming. It explains how to define methods, return values, pass information, and overload methods. It also introduces the main() method and recursion. The document also includes examples.
Full Transcript
This session is about methods. Methods are blocks of codes which can be used as functions: they take as input some parameters and compute some values or perform operations, using these parameters. **[Outline]** 1. Defining methods 2. Returning a value 3. Passing information 4. Overloading m...
This session is about methods. Methods are blocks of codes which can be used as functions: they take as input some parameters and compute some values or perform operations, using these parameters. **[Outline]** 1. Defining methods 2. Returning a value 3. Passing information 4. Overloading methods 5. The main() method 6. Recursion **1. Defining methods** Here is an example of a typical method declaration: public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here } The only required elements of a method declaration are the method\'s return type (here double), name (here calculateAnswer), a pair of parentheses (), and a body between braces {}. More generally, method declarations have six components, in order: 1. Modifiers---such as public, private, and others you will learn about later. 2. The return type---the data type of the value returned by the method, or void if the method does not return a value. 3. The method name---the rules for field names apply to method names as well, but the convention is a little different. 4. The parameter list in parenthesis---a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses. 5. An exception list---to be discussed later. 6. The method body, enclosed between braces---the method\'s code, including the declaration of local variables, goes here. **Definition:** Two of the components of a method declaration comprise the *method signature*---the method\'s name and the parameter types. The signature of the method declared above is: calculateAnswer(double, int, double, double) **Naming a Method** Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized. Here are some examples: run runFast getBackground getFinalData compareTo setX isEmpty Typically, a method has a unique name within its class. However, a method might have the same name as other methods due to *method overloading* (see below). **Exit a Method** A method returns to the code that invoked it when it - completes all the statements in the method, - reaches a return statement, or - throws an exception (covered later), whichever occurs first. **2. Returning a value** We have seen in the previous session two branching statements: break and continue. The last of the branching statements is the return statement. The return statement exits from the current method, and control flow returns to where the method was invoked. The return statement has two forms: one that returns a value, and one that doesn\'t. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. return ++count; The data type of the returned value must match the type of the method\'s declared return value. When a method is declared void, use the form of return that doesn\'t return a value. return; Any method declared void does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method. If you try to return a value from a method that is declared void, you will get a compiler error. Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; The data type of the return value must match the method\'s declared return type; you can\'t return an integer value from a method declared to return a boolean. The following getArea() method returns an integer: // a method for computing the area of the rectangle public int getArea() { return width \* height; } This method returns the integer that the expression width\*height evaluates to. **3. Passing information** You can use any data type for a parameter of a method. This includes primitive data types, such as doubles, floats, and integers and reference data types, such as arrays. Here\'s an example of a method that accepts an array as an argument and return an array. public int\[\] example(int\[\] someArray) { // method body goes here } **Parameter Names** When you declare a parameter to a method, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument. The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method, and it cannot be the name of a local variable within the method. **Passing Primitive Data Type Arguments** Primitive arguments, such as an int or a double, are passed into methods *by value*. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Here is an example: public class PassPrimitiveByValue { public static void main(String\[\] args) { int x = 3; // invoke passMethod() with // x as argument passMethod(x); // print x to see if its // value has changed System.out.println(\"After invoking passMethod, x = \" + x); } // change parameter in passMethod() public static void passMethod(int p) { p = 10; } } When you run this program, the output is: After invoking passMethod, x = 3 **Passing Reference Data Type Arguments** Reference data type parameters, such as arrays (and object - see later), are also passed into methods *by value*. This means that when the method returns, the passed-in reference still references the same array or object as before. *However*, the values in the array (of the object\'s fields) *can* be changed in the method. For example, consider the following method: public void changeArray(int\[\] someArray) { // code to change the first value in the array someArray\[0\] = 2; // code to assign a new reference to the array someArray = new int\[\] {1,2,3,4};\ } Let the method be invoked with these arguments: changeArray({0,0,0,0,0}) Inside the method, someArray initially refers to an array valued {0,0,0,0,0}. The method changes the first value to 2 and thus someArray refers to an array valued {2,0,0,0,0}. This change will persist when the method returns. Then someArray is assigned a reference to a new array with value {1,2,3,4}. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by someArray has changed, but, when the method returns, someArray still references the same array as before the method was called. **Arbitrary Number of Arguments** You can use a construct called *varargs* to pass an arbitrary number of values to a method. You use varargs when you don\'t know how many of a particular type of argument will be passed to the method. It\'s a shortcut to creating an array manually. To use varargs, you follow the type of the last parameter by an ellipsis (three dots, \...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none. public int totalSale(int\... sale) {\ int total = 0; total = total + sale\[1\]; total = total + sale\[2\]; // more method body code follows that returns total } You can see that, inside the method, sale is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case. You will most commonly see varargs with the printing methods; for example, this printf method: public PrintStream printf(String format, Object\... args) allows you to print an arbitrary number of objects. It can be called like this: System.out.printf(\"%s: %d, %s%n\", name, idnum, address); or like this System.out.printf(\"%s: %d, %s, %s, %s%n\", name, idnum, address, phone, email); or with yet a different number of arguments. **4. Overloading Methods** The Java programming language supports *overloading* methods, and Java can distinguish between methods with different *method signatures*. This means that methods within a class can have the same name if they have different parameter lists. Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method---for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list. public class DataArtist { \... public void draw(String s) { \... } public void draw(int i) { \... } public void draw(double f) { \... } public void draw(int i, double f) { \... } } Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types. **Note:** *Parameters* refers to the list of variables in a method declaration. *Arguments* are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration\'s parameters in type and order. You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type. **Note:** Overloaded methods should be used sparingly, as they can make code much less readable. **5. The main method** Although Java is an object orientated language, running a Java program requires that the JVM starts following the instructions in the program from somewhere. This place in the code, described as an entry point, is the main method. public static void main(String \[\] args){ //first instruction here } In the Java programming language, every application must contain a main method whose signature is: public static void main(String\[\] args) The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose \"args\" or \"argv\". The main method is similar to the main function in C and C++; it\'s the entry point for your application and will subsequently invoke all the other methods required by your program. The main method accepts a single argument: an array of elements of type String. public static void main(**String\[\] args**) This array is the mechanism through which the runtime system passes information to your application. For example: java *MyApp* *arg1* *arg2* Each string in the array is called a *command-line argument*. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument: -descending Most of the program you have written so far ignores its command-line arguments, but you should be aware of the fact that such arguments do exist. **6. Recursion** We call recursion the process by which a method can call itself. Working with recursive functions is not without dangers however. A function such as: void printHello(){ System.out.println(\"Hello\"); printHello(); } while recursive in nature (it calls itself) results in an infinite loop equivalent to: void printHello(){ while (true){ System.out.println(\"Hello\"); } } To write a recursive function correctly there must be two elements to the function: - a base case - a recursive case that approaches the base case. A non-infinite verision of the recursive function above would be for example: int count = 0; void printHello(){ count++; if (count \< 5){ System.out.println(\"Hello\"); printHello(); } } which would only call itself while the condition evaluated to true and the condition is such that each call of the function moves the condition closer to evaluating to false. Recursive algorithms can replace loops for example a common example of a recursive algorithm would be to determine if a String is palindromic (i.e. reads the same backwards as forwards). The base case in this algorithm would occur if the String contained 0 or 1 letters. The recursive case would compare the letters at either end of the String and then repeat the comparison on a substring of the original String where the characters at either end had been removed. public boolean isPalindrome(String s){ if(s.length() == 0 \|\| s.length() == 1){ return true; } if(s.charAt(0) == s.charAt(s.length()-1)){ return isPalindrome(s.substring(1, s.length()-1)); } return false; }