120 likes | 258 Views
Introduction to Methods. ICS3M. What is a Method?. A method is a set of instructions that we can call at any point in our program. Methods will have input parameters and return can return an output value. We have already used methods many times before.
E N D
Introduction to Methods ICS3M
What is a Method? • A method is a set of instructions that we can call at any point in our program. • Methods will have input parameters and return can return an output value. • We have already used methods many times before. • Math.pow(), Math.round, System.out.println
What does a method look like? public static void printHeading() { System.out.println(“My Program”); System.out.println(“This is a test”); } I can execute this method in my main program by saying: printHeading();
Methods with Input and Output Information passed into the method goes here. You can pass in more than one variable into a method public static int square(int number) { return number*number; } Note the return statement, the return type, and the input type(s). We can run this code as follows: int x = square(y); Tells Java what this method will return when finished. If it returns nothing, use the word “void” Returns this value at the end of the method
Method ‘Vocabulary’ • Method definition • This is the body of code that makes up the method • Method invocation • This is when we actually call the method (with proper inputs) and run the code inside
Your Task • Complete the “Method Introduction” Worksheet.
More on Methods • The numbers passed into a method call are called parameters: public static int multiply(int a, int b) { return a*b } This method has two integer parameters that must be supplied when calling the method. multiply(5,4);
Method Overloading • The compiler knows what method you want to run by looking at the method name AND its parameters. This allows us to have several methods with the same name. Public static int multiply(int a, int b) Public static double multiply(double a, double b) Public static double multiply (int a, double b)
Variable Scope • What is wrong with the following statements For (int i = 0, i < 10, i ++) { System.out.println(i); } i = i + 1; System.out.println(i) “i” does not exist outside of the {} that it was declared in. If I want to use a new variable called “I”, I can declare it using int i = 1;. The new I does not contain the same value as the original declared in the for loop! These are different numbers!
Variable Scope • Variables only exist in the set of { } that they were created in and any internal { }. (1){ int a, b (2){ int c } int d (3){ int e (4){int f } }(5) } Identify all of the variables available inside each numbered pair of {}. (1) a,b (c d e f not available because we haven’t declared them yet!) (2) a,b,c (3) a,b,c,d,e (4) a,b,c,d,e,f (5) a,b,d (the {} containing c,e,f have all closed, so they are no longer available