Presentation is loading. Please wait.

Presentation is loading. Please wait.

Methods.

Similar presentations


Presentation on theme: "Methods."— Presentation transcript:

1 Methods

2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer. Methods simplify programs. If a specific task is performed in several places in the program, a method can be written once to perform that task, and then be executed anytime it is needed. This is known as code reuse.

3 void Methods and Value-Returning Methods
A void method is one that simply performs a task and then terminates. System.out.println("Hi!"); A value-returning method not only performs a task, but also sends a value back to the code that called it. int number = Integer.parseInt("700.0");

4 Defining a void Method To create a method, you must write a definition, which consists of a header and a body. The method header, which appears at the beginning of a method definition, lists several important things about the method, including the method’s name. The method body is a collection of statements that are performed when the method is executed.

5 Two Parts of Method Declaration
Header public static void displayMesssage() { System.out.println("Hello"); } Body

6 Parts of a Method Header
Method Modifiers Return Type Method Name Parentheses public static void displayMessage () { System.out.println("Hello"); }

7 Parts of a Method Header
Method modifiers public—method is publicly available to code outside the class static—method belongs to a class, not a specific object. Return type—void or the data type from a value-returning method Method name—name that is descriptive of what the method does Parentheses—contain nothing or a list of one or more variable declarations if the method is capable of receiving arguments.

8 Calling a Method A method executes when it is called.
The main method is automatically called when a program starts, but other methods are executed by method call statements. displayMessage(); Notice that the method modifiers and the void return type are not written in the method call statement. Those are only written in the method header.

9 Calling a Method public class SimpleMethod {
public static void main(String[] args) System.out.println(“Hello from the main method!”); displayMessage(); System.out.println(“Back in the main method.”); } public static void displayMessage() System.out.println(“Hello from the displayMessage method!”);

10 Hierarchical Method Calls
public class DeepAndDeeper { public static void main(String[] args) System.out.println(“I am starting in main.”); deep(); System.out.println(“Now I am back in the main method.”); } public static void deep() System.out.println(“I am now in deep.”); deeper(); System.out.println(“Now I am back in deep.”); public static void deeper() System.out.println(“I am now in deeper.”); 1 2 7 2 3 4 6 4 5

11 Documenting Methods A method should always be documented by writing comments that appear just before the method’s definition. The comments should provide a brief explanation of the method’s purpose. The documentation comments begin with /** and end with */.

12 Documenting Methods public class SimpleMethod {
public static void main(String[] args) System.out.println(“Hello from the main method!”); displayMessage(); System.out.println(“Back in the main method.”); } /** The displayMessage method displays a greeting */ public static void displayMessage() System.out.println(“Hello from the displayMessage method!”);

13 Method Overloading

14 Method Overloading A class may define multiple methods with the same name- --this is called method overloading usually perform the same task on different data types Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);

15 Method Overloading: Signature
The compiler must be able to determine which version of the method is being invoked This is by analyzing the parameters, which form the signature of a method the signature includes the type and order of the parameters if multiple methods match a method call, the compiler picks the best match if none matches exactly but some implicit conversion can be done to match a method, then the method is invoke with implicit conversion. the return type of the method is not part of the signature

16 double tryMe (int x) { return x ; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32) Invocation

17 Which tryMe will be called?
More Examples double tryMe ( int x ) { return x + 5; } Which tryMe will be called? tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); double tryMe ( double x ) { return x * .375; } double tryMe (double x, int y) { return x + y; }

18 Variable Scoping

19 There are two types of scopes in Java
At a given point, the variables that a statement can access are determined by the scoping rule the scope of a variable is the section of a program in which the variable can be accessed (also called visible or in scope) There are two types of scopes in Java class scope a variable defined in a class but not in any method block scope a variable defined in a block {} of a method; it is also called a local variable

20 Java Scoping Rule A variable with a class scope
class/static variable: a variable defined in class scope and has the static property it is associated with the class and thus can be accessed (in scope) in all methods in the class instance variable: a variable defined in class scope but not static it is associated with an instance of an object of the class, and thus can be accessed (in scope) only in instance methods, i.e., those non-static methods A variable with a block scope can be accessed in the enclosing block; also called local variable a local variable can shadow a variable in a class scope with the same name Do not confuse scope with duration a variable may exist but is not accessible in a method, e.g., method A calls method B, then the variables declared in method A exist but are not accessible in B.

21 Scoping Rules (cont.): Variables in a method
There can be three types of variables accessible in a method : class and instance variables static and instance variables of the class local variables those declared in the method formal arguments

22 Example1: instance variables formal arguments local variables
public class Box { private int length, width; public int widen (int extra_width) private int temp1; size += extra_width; } public int lenghten (int extra_lenth) private int temp2; size += extra_length; instance variables formal arguments local variables

23 Instance variables are accessible in all methods of the class
public class Box { private int length, width; public int widen (int extra_width) private int temp1; size += extra_width; } public int lenghten (int extra_lenth) private int temp2; size += extra_length; Instance variables are accessible in all methods of the class formal arguments are valid within their methods Local variables are valid from the point of declaration to the end of the enclosing block

24 public class Test { final static int NO_OF_TRIES = 3; static int i = 100; public static int square ( int x ) // NO_OF_TRIES, x, i in scope int mySquare = x * x; // NO_OF_TRIES, x, i, mySquare in scope return mySquare; } public static int askForAPositiveNumber ( int x ) for ( int i = 0; i < NO_OF_TRIES; i++ ) { // NO_OF_TRIES, x, i in scope; local i shadows class i System.out.print(“Input: “); Scanner scan = new Scanner( System.in ); String str = scan.nextLine(); int temp = Integer.parseInt( str ); // NO_OF_TRIES, x, i, scan, str, temp in scope if (temp > 0) return temp; } // NO_OF_TRIES, x, i in scope return 0; } // askForPositiveNumber public static void main( String[] args ) {…}

25 Passing Arguments to a Method
Values that are sent into a method are called arguments. System.out.println("Hello"); number = Integer.parseInt(str); The data type of an argument in a method call must correspond to the variable declaration in the parentheses of the method declaration. The parameter is the variable that holds the value being passed into a method. By using parameter variables in your method declarations, you can design your own methods that accept data this way.

26 Passing Arguments to a Method
public class PassArg { public static void main(String[] args) int x = 10; displayValue(x); displayValue(x * 4); } public static void displayValue(int num) System.out.println(“The value is: ” + num);

27 Passing 5 to the displayValue Method
public static void displayValue(int num) { System.out.println("The value is " + num); } The argument 5 is copied into the parameter variable num. The method will display: The value is 5

28 Argument and Parameter Data Type Compatibility
When you pass an argument to a method, be sure that the argument’s data type is compatible with the parameter variable’s data type. Java will automatically perform widening conversions, but narrowing conversions will cause a compiler error. double d = 1.0; displayValue(d); Error! Can’t convert double to int

29 Passing Multiple Arguments
The argument 5 is copied into the num1 parameter. The argument 10 is copied into the num2 parameter. showSum(5, 10); public static void showSum(double num1, double num2) { double sum; //to hold the sum sum = num1 + num2; System.out.println("The sum is " + sum); } NOTE: Order matters!

30 Arguments are Passed by Value
In Java, all arguments of the primitive data types are passed by value, which means that only a copy of an argument’s value is passed into a parameter variable. A method’s parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call. If a parameter variable is changed inside a method, it has no affect on the original argument.

31 public class PassArg { public static void main(String[] args) int number = 99; System.out.println(“Number is “ + number); changeMe(number); } public static void changeMe(int myValue) System.out.println(“I am changing the value.”); myValue = 0; System.out.println(“Now the value is “ + myValue); Program output Number is 99 I am changing the value Now the value is 0 Only a copy of an argument’s value is passed into a parameter variable

32 Passing Object References to a Method
Recall that a class type variable does not hold the actual data item that is associated with it, but holds the memory address of the object. A variable associated with an object is called a reference variable. When an object such as a String is passed as an argument, it is actually a reference to the object that is passed.

33 Passing Arguments by Reference
public class Swap { public int x; public static void swap(Swap s1, Swap s2) { int temp = s1.x; s1.x = s2.x; s2.x = temp; }

34 class SwapTest{ public static void main(String args[]) { Swap a1 = new Swap(); // creating object Swap a2 = new Swap(); a1.x = 2; // assigning value to data field a2.x = 5; System.out.println("Before swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); Swap.swap(a1.x,a2.x); System.out.println("After swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); } } Output:??

35 class SwapTest{ public static void main(String args[]) { Swap a1 = new Swap(); // creating object Swap a2 = new Swap(); a1.x = 2; // assigning value to data field a2.x = 5; System.out.println("Before swap"); Output: Before swap a1.x=2 a2.x=5 After swap a1.x=5 a2.x=2 System.out.println("a1.x="+a1.x+" a2.x="+a2.x); Swap.swap(a1.x,a2.x); System.out.println("After swap"); System.out.println("a1.x="+a1.x+" a2.x="+a2.x); } }

36 Arguments passing by value and reference exercise
Write a void method (call it argumentExample) that takes an integer argument, modifies its value to be twice as much as originally, and prints it. In your main method, create an int variable int Num = 50, then call argumentExample (Num), then print the variable myNum below that. What do you observe? Write a few words about what is happening as a block comment above this method in your code.

37 Arguments passing by value and reference exercise
Now change the above example program In class, declare an instance variable Number of int type. Define a one argument constructor which sets the initial value of Number variable passed at the time of object creation. Call argumentExpamle method and pass object of the class as an argument, method should receive object and change the value instance variable and return object back to main. Print value of variable before and after argumentExample method call. See how output is different in both programs.

38 Reference Chapter 5 & 9, Introduction to Java Programming, Liang.


Download ppt "Methods."

Similar presentations


Ads by Google