Vous êtes sur la page 1sur 4

Notes on JAVA 10.2005.

9: Methods

A method
is a subprogram and therefore has a very similar syntax to the main method, has its own name, has its own {} block , is defined before or after the main program, is only executed when the main method (or another method) calls the method by its name.

There are TWO types of methods:


void methods that do something (e.g. printing something to screen or modifying an object), and return methods that compute a new value and return that to the main or calling method. 1) 2) 3) There are many standard methods in the many different Java classes, e.g. Math.random (); System.out.println (); Many methods just do something, e.g. System.out.println (); or just return a value, e.g. Math.random ();. They are always followed by empty brackets. Many methods, however, have to receive data or values to act upon. E.g. to call the Math.sqrt (); method without a value would be meaningless. After all, what square root do you want? So you have to sent it the value (the API defines it as a double), e.g. Math.sqrt (4.0);. Both types of methods may use such values (called parameters) from the calling method to influence the way they do their task. Compare the effect of System.out.println (); and System.out.println (Hello world!);, or double r = Math.random ();. and double s = Math.sqrt (4.0);.

4)

Parameters

are used to communicate data/values to a method, must be listed in brackets in the method call then known as actual parameters. when writing your own method they must be listed in brackets immediately behind the method name then known as formal parameters,

must match in number, type, and order, their names should differ from each other, the program maps them from list to list without caring about their names, it only cares about number, type, and order (if they are of different type).

Formal and actual parameters

Two types of parameters:


Often a method needs incoming data or an object to act upon. Primitive data types are communicated as value parameters, i.e. the actual value is passed to the method. A duplicate of the data is created and passed to the method. Objects are communicated as variable parameters, i.e. they are not passed directly to a method but their memory address is. The method then accesses the object to retrieve information from it or make changes to it. This saves memory, as no duplicate of the object (or an array of objects) has to be created and passed about. Variables Parameters Value parameters Variable parameters identifiers declared within a program/subprogram block. identifiers used to send data to a method. primitive types passed to a method as duplicates. objects passed to a method by memory address only.

Summary:
A program (class) may contain one and only one main method. In addition to the main method, a class may also contain any number of subprograms (methods). The main method is the part of the program that runs first and calls the subprograms (if there are any). Subprograms are distinct from the main method, and run only when called upon. The main method can run only once (although it may contain repetition structures), whereas a method may be called as often as necessary / as you like.

Notes on JAVA: Methods

Page 2 of 4

Advantages:
The program is more clearly organised and therefor easier to understand and debug. The main program is shorter and clearer. Methods are easily reused in other programs. This is called modular construction. By giving a name to the computation of a value, we make it easier to refer to that computation. Code that uses clearly named methods is often easier to understand than code that performs all computations in the main program. If a method performs the computation, the program can repeat the computation over and over by simply calling the method repeatedly. The code for the computation need not be reproduced every time it is needed.

Void Methods:

A void method is a subprogram that does something or modifies an object. [Lets do the object modification when we deal with objects in detail.] The most common void methods print something to screen or set some colours, fonts, etc in a graphic environment. Writing a void method: 1) Started with the reserved words public static . 2) The reserved word void to indicate that nothing is returned. 3) Method name, e.g. printCentered. 4) List of parameters needed for the method (Use local names!) and their type in brackets. e.g. (String s); 5) { to start the method block. 6) The block which does something. 7) } to end the method block. Example of the void method printCentered: public static void printCentered (String s) { int widthOfScreen = 80; String spaces = ""; for (int i = 0; i < (widthOfScreen s.length) / 2; i++) spaces = " " + spaces; System.out.println (spaces + s); } Calling a void method: 1) We just call the method by name on a new line, followed by brackets () followed by a semicolon, e.g. System.out.println (); 2) Most of the time a parameter (sometimes more than one) is placed between the brackets, e.g. String sentence = Playing of computer games is strictly prohibited!; System.out.println (sentence); printCentered (sentence); printCentered (Hello world!);

Return Methods:
A return method is a subprogram that returns a value associated with the methods own name. A return method can, therefore, return only ONE value, namely the one associated with its name. A return method has a type, which is the type of the value returned by the method. Multiple return methods using the same name may be created, but they must accept different parameters. The combination of method name and parameters is called signature. (This is method overloading.) A return method is called as it is in mathematics, by naming the method followed by its actual parameter list. A return method call can be placed in any expression of the same type.

Notes on JAVA: Methods

Page 3 of 4

Writing a return method: 1) Started with the reserved words public static . 2) The type of the result of the method. As a method is to return a value, so its type must be declared, e.g. int 3) Method name, e.g. areaOfRectangle. 4) List of parameters needed for the method (Use local names!) and their type in brackets. e.g. (int len, int bre); 5) { to start the method block. 6) The block which MUST assign a value to a variable of the type you want to return (usually done in the second last line), e.g. int a = len * bre; 7) The last line will be the return, e.g. return a; 8) } to end the method block. Example of multiple return methods all with the same name (BUT with different signatures): public static int areaOfRectangle (int len, int bre) { int a = len * bre; return a; } public static double areaOfRectangle (double len, double bre) { double a = len * bre; return a; } public static int areaOfRectangle (double len, double bre) { double ad = len * bre; int ai = (int) ad; // int a = (int) len * bre; return ai; // return a; } Calling a return method: 1) We may assign the methods value to another variable in the program, e.g. area = areaOfRectangle (length, breadth); and then use that variable to continue. 2) We can call the method directly in another statement, either for output purposes or for further calculation: example 1: System.out.println (The area of the rectangle is + areaOfRectangle (length, breadth) + m2.); example 2: costOfPloughing = areaOfRectangle (length, breadth) * costPerSquareMeter; (This is known as a nested call.)

Method overloading
Java allows a class/program to have more than one method with the same name, as long as the method signature differ in the parameters either in the number of parameters or the types of parameters. The compiler chooses the correct method based on the parameters provided in the method call, i.e. the signature. This technique is called overloading, which is related to polymorphism. Examples of this are the various Math.min () methods (the signature varies in the types of the formal parameters): public static double min (double a, double b) public static float min (float a, float b) public static int min (int a, int b) public static long min (long a, long b) Returns the smaller of two double values. Returns the smaller of two float values. Returns the smaller of two int values. Returns the smaller of two long values

Notes on JAVA: Methods or the two string.indexOf () methods (the signature varies in the number of formal parameters): public int indexOf (String str)

Page 4 of 4

Returns the index within this string of the first occurrence of the specified substring. Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

public int indexOf(String str, int fromIndex)

Many more examples can be found in the various Java classes. Browse the API to find more.

Exercises:
1. Write a modular program that converts weight in pounds to kilograms, using a method to calculate the number of kilograms. (1 lb = 0.45359 kg) Write a method called celsiusToFahrenheit that converts Fahrenheit temperatures to Celsius. Write a short program to test it. (freezing point = 0oC = 32oF, boiling point = 100oC = 212oF) Write and test a program containing a method named averageOfThree, which receives three values named num1, num2, and num3, returning their average.

2.

3.

3a. Write and test a method that receives an array of numbers (an object!) and returns their average. 4. Write multiple methods called cubeOf that return the cube of a double, a float, and an int. For example, cubeOf (1.1) should return 1.331. Write a short program to test your methods. The amount of money accumulated after the principal sum, p, is invested for n years at a simple annual rate of r is p(1 + nr). Write and test a method that receives p, n, and r as parameters, returning this amount. Write an Area class containing a triangle method, a circle method, etc, each computing the area of the required shape. The Area class does not need a real main method, thus serving as a library of useful area calculations. Write a short CalculateAreas class program to test your methods in the Area class. The call will then be Area.triangle, Area.circle, etc.

5.

6.

6a. Expand the Area class by adding multiple triangle methods, multiple circle methods, etc, each catering for different data types. 7. Write a method that sorts an array of integers.

_________________________________________________

mb

Vous aimerez peut-être aussi