Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture 4 Methods Introduction to Modular Programming Methods Concept • A method is a collection of statements that are grouped together to perform a task • A method is a program module that contains a series of statements that perform a task. • To execute a method, it has to be invoked or called from another method • The calling method makes the method call, and this call invokes the called method • When the System.out.println method is called, the system executes other statements in order to display a message on the console Method Features • Every method must include the following features: – – – – A declaration (header or definition) An opening curly bracket A body A closing curly bracket • The method declaration is the first line of the method • It is also known as the method header and includes – – – – – – Optional access modifier (i.e. public, private, protected) The return/data type of the method (void, int, double, String etc) The name of the method An opening parenthesis An optional list of arguments(comma separated if more than one) A closing parenthesis Method Syntax • In general a method has the following syntax modifier returnValueType methodName(param1, param2, ..paramN) { // method body } Access Modifiers • The access modifiers for Java methods include public, private and protected • The access modifier tells the compiler how to call the method • Methods are most often defined to be public • Defining methods as public means that any class can use it • Any method that can be used without creating an object must be defined as static • Methods declared as static are known as class methods Return Value Types • Some methods may return values after they have completed their tasks • The value returned has the same data type as the return value type of the method • Some methods do not return values after they complete their tasks. • The return value types for methods that do not return data are always void • As noted earlier, the main method for every Java application has the void return type The return Statement • The return statement is used in nearly all methods except those methods declared as void • The return statement is usually not required in methods declared as void • The return statement is usually the last statement in the method • An attempt to use more than one return statement in a method can result in a compile time error • The return statement can be used to return a value at the end of the method execution Method Parameter List • The parameter list is contained in the parenthesis that follows the method name in a method declaration • The variables defined in the method header are known as formal parameters or simply parameters • The parameter list refers to the data type, the order and number of variables declared in the parenthesis • Each parameter must be declared with its own data type and must be separated from others by a comma • The method name and the parameter list form the method signature or method header • Parameters are optional; that is, some methods may not contain parameters Java methods example • In java, methods are housed within a program unit called classes • Classes can contain one or more methods for performing various tasks belonging to the class • As an example, a class that represents a bank account may have various methods – A method to deposit some amount to the account – A method to withdraw some money from the account – A method to check the current balance of the account • Each method is invoked by an object to perform an action through a method call Method Call • Any class can contain any number of methods • Each method in a class can be called an unlimited number of times • Some methods require some data items (known as arguments or parameters) in order to perform their tasks • Other methods do not require arguments to perform their tasks • Some other methods send back data (known as returning values) to the calling methods • Other methods do not return values to the calling methods Method call Illustrated Pass the value of a to n1 Pass the value of b to n2 public static void main(String[ ] arg) { public static int min( int n1, int n2 ) { int small ; int a = 7; int b = 9; int c = min( a, b ); System.out.println( “The smallest of ” + a + “ and ” + b + “ is ” + c ); } if( n1 < n2 ) small = n1; else small = n2; return small; } Methods as Behaviours • Recall that main is a special method that is always called automatically by the Java Virtual Machine (JVM) at execution • Unlike main, most methods do not get called automatically • Methods must be called by objects to tell them to perform their tasks • The name of the object or class is followed by a period and the name of the method as in firstName.toUpperCase() and Integer.parseInt() • Methods determine the behaviour or actions performed by an object or a class as a whole unit Methods Declaration • A method whose declaration is preceded by the keyword public indicates that the method is available to the public • Methods declared as public can be called from within the same class and by objects or methods of other classes • Methods declared as void do not return (give back) any value after completing their tasks • Methods that have return types other than void can return values after completing their tasks • The values returned can be one of simple types such as int, double, String, boolean or an object of a class Methods Declaration continued • By convention method names begin with lowercase letters and all subsequent words in the name begin with uppercase letters – camel notation • The name of the method follows the return type • Method names are followed by a set of parentheses • Methods with empty set of parenthesis indicate that the methods do not require additional information to complete their task • The body of the method contains the statements that perform the task of the method • Every method’s body is enclosed in a set of left and right braces ( { and } – a set of curly brackets ) Declaring Methods • Consider the following parts in the method below: the return type, the name, the arguments, and the body: Access modifier type public { void name arguments displayJobs( void ) // set of statements that perform the tasks of method Body } System.out.println(“Cooks wanted”); • As noted earlier, the type, name and arguments together form the signature of the method or method header Sample Method Declaration • Note the use of the 4 method parts below • The return type, the name, the arguments, and the body: public void setAge( int age ) { // statements that perform the task of the method int itsAge = age; } • The type, name and arguments together is referred to as the signature of the method, or the method header static Methods, static Fields, class Math • Most methods execute in response to method calls by some specific objects • Other methods do not require the call from an object in order to perform their tasks • Such methods apply to the class in which they are declared • They are therefore known as static methods or class methods • Methods declared as static can be called without creating an instance of the class that creates them • All static methods are declared by placing the keyword static before the return type static Methods continued • Static methods can be called by specifying the name of the class in which they are declared, followed by a dot (.) and the name of the method ClassName.methodName( arguments ) • The Math class contains a number of static methods for most common mathematical calculations • The square root method is a good example of a static method in class Math • As an example, a static method call can evaluate the square root of 400.0 as follows Math.sqrt( 400.0 ) will produce 20.0 static Fields • • • • • • • • The term field is used to describe class variables Class variables are also know as instance variables Instance variables are tied to specific instances of a class Instance variables are not shared among objects of the same class Instance variables are stored in different locations in the computer memory Static variables store values in a common memory location Static fields allow data sharing among class members If one class member changes the value of a static variable all other objects of the class are affected class StaticFieldDemo { int a; static int b; // any change to b affects all other class object values public static void main( String[ ] args ) { StaticFieldDemo aVar = new StaticFieldDemo(); StaticFieldDemo bVar = new StaticFieldDemo(); aVar.a = 5; // assign aVar variable a to 5 bVar .a = 8; // assign bVar variable a to 8 independent of a aVar.b = 15; // assign aVar variable b to 15 bVar.b = 18; // is automatically assigned the value 18 } } The Square Root Method • Method sqrt takes an argument of type double and returns a result of type double • The method can be invoked by the standard output method as follows System.out.println( Math.sqrt( 400.0 ) ); • In this case the value returned by method sqrt() becomes the argument to method println() • Please note that the call to method sqrt() did not require the creation of a Math object • Also all Math class methods are static – therefore each method is called by preceding the method name by the class name Math followed by the dot operator Class Math Methods • Class Math is part of the java.lang package which is implicitly imported by the compiler • Therefore we do not need to import class Math in order to use its methods • Some common class Math methods include – – – – – – – – – – Math.pow( x, y ) evaluates x raised to the power y (i.e., xy) Math.max( x , y ) determines larger value of x and y Math.min( x, y ) determines smaller value of x and y Math.sqrt( x ) evaluates square root of x Math.exp( x ) exponential method ex Math.log( x ) natural logarithm of x (base e) Math.floor( x ) rounds x to the largest integer not greater than x Math.ceil( x ) rounds x to the smallest integer not Math.abs( x ) absolute value of x Math.sin( x ) trigonometric sine of x (x in radians) Method Overloading • It is possible to define two or more methods with the same name but have different parameter list • The methods can have the same name but the number of parameters may vary • Such methods are known as overloaded methods • Overloaded methods must have different parameter lists • Different return types or modifiers are not enough for overloading a method • Methods that perform closely related tasks should be given the same name • This concept can be applied to different Constructors in a class definition Overloaded Methods Method with int arguments int sum( int a, int b ) { return a + b; } Method with double arguments double sum( double a, double b) { return a + b; } If the method sum is called with int parameters, the sum method that expects int parameters will be invoked. If the method sum is called with double parameters, the sum method that expects double parameters will be invoked. The java interpreter determines which method is used based on parameter list Method overloading refers to two or more methods with the same name, but different parameter list. The Scope of a Variable • The scope of a variable is the part of the program where the variable can be referenced • Any variable declared inside a method is referred to as a local variable of the method • The scope of a local variable starts from the point of its declaration to the end of the block that contains the variable • A local variable must be declared before it can be used in a program • Parameters of a method are also local variables of the method More on scope of Variables • The scope of method parameters covers the entire method • Any variable declared in the initial part of a for loop header has its scope in the entire loop • A variable declared inside a for loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable • A variable can be declared a number of times in different non-nesting blocks in a method or a loop Access Modifiers • Java provides several modifiers that control access to data, methods and classes • The public, private and default modifiers are discussed below – The public modifier makes classes, methods and fields accessible from any class – The private modifier makes methods and fields accessible from only within the class that declares or creates them – If public or private is not specified, the default access is within package level. It is therefore known as package – private or package access – The protected modifier gives access to same package or subclass level access The Return Type of a Method • The return type of a method may be any data type. • The type of a method indicates the datatype of the output it produces. • Some methods return nothing in which case they are declared as void. The return Statements • The return statement is used in a method to output the result of the methods computation. • It has the form: return expression_value; • The type of the expression_value must be the same as the type of the method: double calcCube(double aNumber) { double answer; // Compute the cube of aNumber and assign // the result to the variable answer answer = aNumber * aNumber * anumber; return answer ; } The return Statement continued • A method exits immediately after it executes the return statement • Therefore, the return statement is usually the last statement in a method • A method may have multiple return statements. Can you think of an example of such a case? Sample • Example: int absoluteValue(int anyNumber) { if (anyNumber < 0) return –anyNumber; else return anyNumber; } void Methods • A method of return type void does not require the return statement in its body of statements. • A good example is when a method’s task is only to print to the screen. • Other situations in which methods are declared void is when the method is used to set or assign a value to an expression • If no return statement is used in a method of type void, it automatically exits at the end of the method Method Arguments • Methods can accept input in the form of arguments. • Arguments can be used as variables inside the method body. • Like variables, arguments, must have their type specified. • Arguments are specified inside the parentheses that follow the name of the method. Example of a Method • Here is an example of a method that divides two doubles: double divide(double a, double b) { double answer; answer = a / b; return answer; } Method Arguments • Multiple method arguments are separated by commas: double Math.pow(double x, double y) • Arguments may be of different types String studentInfo( String name, int age ) The Method Body • The body of a method is a block specified by curly brackets. The body defines the actions of the method. • The method arguments can be used anywhere inside of the body. • All methods must have curly brackets to specify the body even if the body contains only one or no statement. main - A Special Method • The only method that we have used in lab up until this point is the main method. • The main method declared in java applications as public static void main(String [] arg ) is the starting point of every java application • The java command executes the Java Virtual Machine (JVM) as in java ClassName arg1 arg2 … • The JVM in turn loads the class specified by ClassName and uses that class name to invoke the method main • Declaring the method main as static allows the JVM to invoke main without creating an instance of the specified class main continued class SayHello { public static void main(String[] args) { System.out.println("Hello, " + args[0]); } } • When a java Program arg1 arg2 … argN is typed on the command line, anything after the name of the class file is automatically entered into the args array as in: java SayHello Sam • In this example args[0] will contain the String "Sam ", and the output of the program will be Hello, Sam . Example main method class Greetings { public static void main( String[] args ) { String greeting = ""; for (int i=0; i < args.length; i++) { greeting += "Jambo " + args[i] + "! "; } System.out.println(greeting); } } • After compiling, if you type java Greetings Alice Bob Charlie prints out "Jambo Alice! Jambo Bob! Jambo Charlie!" Recursive Example class Factorial { public static void main (String[] args) { int num = Integer.parseInt(args[0])); System.out.println( fact( num ) ); } static int fact( int n ) { if ( n <= 1 ) return 1; else return n * fact( n – 1 ); } } • After compiling, if you type java Factorial 5 the program will print out 120 Another Example class MaxNum { public static void main( String[ ] args ) { if ( args.length == 0 ) return; int maxNum = Integer.parseInt( args[0] ); for ( int i = 1; i < args.length; i++ ) { if(Integer.parseInt( args[ i ] ) > maxNum ) { maxNum = Integer.parseInt(args[i]); } } System.out.println( maxNum ); } } • After compiling, if you type java MaxNum 3 2 9 2 4 the program will print out 9 Summary • Methods perform all the tasks required of the program • Methods describe all the mechanisms to be performed • Methods in Java have 4 parts: return type, method name, arguments, and method body. • The return type and arguments may be either primitive data types or complex data types (Objects) • Declaring the method main as static allows the JVM to invoke main without creating an instance of the specified class • main is a special Java method which the java interpreter looks for when you try to run a class file • Methods must be called by objects to tell them to perform their tasks