Click here to load reader

Introduction to Methods

  • Upload
    turi

  • View
    94

  • Download
    0

Embed Size (px)

DESCRIPTION

Introduction to Methods. CS0007: Introduction to Computer Programming. Methods. So far in this course we have seen methods in two ways: We’ve used predefined methods from the Java API: System.out.println Math.sqrt We have created a method named main in every program we’ve written. - PowerPoint PPT Presentation

Citation preview

PowerPoint Presentation

CS0007: Introduction to Computer ProgrammingIntroduction to Methods1MethodsSo far in this course we have seen methods in two ways:Weve used predefined methods from the Java API:System.out.printlnMath.sqrtWe have created a method named main in every program weve written.Now we will learn to create our own methods that can be used just like any from the Java API.So what are methods exactly?Methods are a collection of statements that perform a specific task.Why do we have methods?Methods break problems in smaller, more manageable, subproblems.Where have we seen this before?Hierarchy Charts!Methods and Hierarchy ChartsPostage Stamp ProgramCalculate StampsDisplay StampsInputRead SheetsValidate SheetsSet Stamps = Sheets/5Round Stamps to the next whole numberDivide and Conquer and Modular DesignInstead of writing one long method that contains all of the statements necessary to solve a problem, you can write several small methods that solve each specific part of the problem.This is what is known as divide and conquer approach to programming.When you use divide and conquer to design a program, this is known as Modular Design.As a result, each subproblem is known as a module.These modules can easily be implemented as their own methods!Programs that follow modular design principles have benefits:They are easier to write.They are easier to understand.They are easier to debug.They are easier to change.They have parts that can be reused.After learning about methods, you are required to design and implement your programs according modular design principles.void Methods and Value-Returning MethodsThe reason why these structures are called methods is because they reside in classes.This is because in Java almost everything resides in a class.In other Non-Object-Oriented languages, we would call these structures functions and subprocedures, but instead we call them void methods and value-returning methods.void methods simply perform a task then terminate.value-returning methods not only perform a task, but also send a value back to the code that called it.For example:You can perform all output in a void method because it doesnt require and result to be used.Math.sqrt returns a value back to where it was called (For instance, Math.sqrt(9) returns 3 to where it was called).Key terms:CallReturnMethod DefinitionBefore you can use a method you must define it.A method definition has two parts:Method header appears at the beginning of the method definition and several important things about the methodMethod body the collection of statements to be executed when the method is called. It is enclosed in curly braces.Again, weve seen this before:public static void main(String[] args) {...}

Method DefinitionGeneral form of a method:methodModifiers returnType name (parameterList) {body}methodModifiers Keywords that define specific attributes about the method.returnType If the method is value-returning the data type of the returned value goes here. If it is a void method, the keyword void goes here.name Any valid identifier that will be used as the name of the method. Again, it should be descriptive of what the method does, and often should be a verb.parameterList Methods are capable of receiving outside information called arguments. They are assigned to the methods parameters. If the method does not receive any arguments, there is nothing inside of the parentheses. We will discuss arguments and parameters later. Method Examplepublic static void displayMessage(){System.out.println("Hello from the displayMessage method!");}public and static are method modifiers. In short public makes the method available for use outside of the class, and static means that it belongs to the class itself and not individual objects.void is the return type meaning this method does not return a value. displayMessage is the name of the method This method does not take any arguments.Method CallA method is only executed when called.The only exception to this is the main method, which is executed when the program is run.When the JVM sees a method call, it branches to the statements inside of the method.To call a method, you must use its name and supply it with arguments if the method expects them.General form of a method call:name(argumentList);If the method definition has nothing for its parameter list, then you do not need to supply an argument list.

Method ExampleNew Topics:MethodsArguments and ParametersMethods declared outside of one another have different scope:public static void method1() {int x;method2();}public static void method2() {int y;}method2 cannot see method1s local variable x, even though method2 is called from method2. Similarly, method1 cannot see method2s local variable y.General Rule: Local variables declared inside of a method cannot be seen outside of the method it was declared in. So how can methods pass data from one to another?First part of the answer: the caller can pass data to the callee in the form of arguments.An argument is data passed to a method during a method call.

Arguments and ParametersWeve passed arguments to methods before:System.out.println("Hello");Math.sqrt(9);"Hello" and 9 are data we passed the println and sqrt methods that is used to perform their desired functions.These arguments are then stored as local variables that can be used corresponding definition.These local variables are called parameters.Parameters appear in the method header and can be used anywhere in the method definition.Arguments and Parameterspublic static void method1() {int x = 5;method2();}public static void method2() {int y = x;}

method2() cannot see x because it is out of scope, so this is an error.Arguments and Parameterspublic static void method1() {int x = 5;method2(x);}public static void method2(int myX) {int y = myX;}method1 passes the local variable x as an argumentmethod2 takes an integer parameter called myX When method1 calls method2, the value stored in x is sent to the parameter myX so that method2 can use it.Note: arguments can be any expression that resolves to the type that corresponds to the called methods parameter.

Arguments and Parameters ExampleNew Topics:Arguments and ParametersArgument and Parameter NotesTerminology varies for what people call arguments and parameters, but what is important is that you remain consistent.The argument must be some expression that is of the same type as the corresponding parameter OR some type of lower rank.Java will automatically perform widening conversions.Java WILL NOT perform narrowing conversions.Parameters have the same scope as local variables declared in the method.To pass an array variable as an argument, you can simply pass the variable by name.The corresponding method parameter looks very much like a normal parameter, but with [] between the parameter data type and the parameter nameThere are many, many more nuances to arguments and parameters, but we will cover them later.Passing Multiple ArgumentsJava also allows for the passing of multiple arguments to a single method:public static void method1() {method2(1, 2);}

public static void method2(int x, int y){int z = x + y;}The arguments in the method call, as well as, the parameters in the method header are both separated by commas.The arguments values are passed to the corresponding parameters in the order in which they are arranged from left to right.For example, x would get the value 1 here and y would get the value 2.Example: MultipleArgs.javaReturning ValuesMethods may also pass data back to where it was called.This is called returning a value.Weve seen this before:Math.sqrt(9)This method call returns the value of 3 back to where it was called.There are two differences when writing value returning methods:Instead of void as the return type, now that should be whatever type the value you want to return will beYou must use a return statement to return a value at some point for all possible branches in the method definition.Returning Valuespublic static int addOne(int x) {return x+1;}The int after static indicates that this method will return a value of type int.return x+1; is a return statement.return is a keyword that indicates that the result of the expression following it will be returned to where the method was calledSo in this case, the result of x+1 will be returned to where it was calledYou can have as many statements as you like leading up to the return statement, but all branches that are possible in the method definition should end in a return statement.Once a return statement is reached, the programs control flow leaves the method and goes back to where it was called.The expression following the return statement must be the same type as the return type for the method, or one of a lower rank.Calling a Value-Returning MethodIts often the case that you want to do something meaningful with the value a value-returning method returns.You can assign the return value to a variable:double x = Math.sqrt(9);You can use it in an expression:double x = Math.sqrt(9) * 2;You can print it to the screenSystem.out.println(Math.sqrt(9));You can use it anywhere a value of the return type can be used

Value-Returning Method ExampleNew Topics:Value-Returning Method