text: Programs we write to solve a real world problems are actually much larger than the programs we have learned so far. As we know solving a problem starts from the first line of code and large programs are an illusion of many a smaller pieces of code compiled as a group that gives the idea of a larger problem scenario. It is like taking care of the words with the view of creating a bigger sentence. Thus to penetrate the problem, we simply follow the technique – divide and conquer through methods.
  What is a Method?
  Methods are nothing but a modular self-contained units with a view to solve a particular task. They are also referred to as functions or procedures. (We shall be using the name function or methods interchangeably).
  Why Methods?
  But, the question is why do we need to segregate a program into module by means of a method? Well, one of the clear motivation is – divide and conquer. Another, is to enhance software re-usability. Once a method is written to solve a particular task, it can be used as a building block in creating some new programs. The whole gamut of modular programming encircles around the concept of re-usability. Last but not the least, there is another motivation – dividing a program into meaningful methods makes the program easier to maintain and debug. So you see, modularity or breaking the program into meaningful blocks by means of method is very important not only in Java, but also to any other programming language.
  We know it, don't we? We have been writing methods all the time till now. See the first program or pretty much any program you have written so far, there is the function called main written as
  public static void main(String[] args) { // ... }
  This main is nothing more than a function like any other function but with a one very significant difference – Java application always starts from this main function. That's alright but what about re-usability? Well, we also know that, in fact we were re-using it all the time. Recall the function we use to print in Java programs
  System.out.println("Hello");
  The println is nothing but a function which prints whatever we want in the standard output. There are several such functions declared in the Java API library. You may browse through javadoc to see the list of functional available.
  Method structure
  A method or a function signature three parts namely, return type, function name and parameter(s) or argument(s) in the order as follows:
  <return type><function-name>(<argument1>,
  <argument2>,...) {
  //... function body
  }
  The return type may be of any primitive type or object, function name can be any name adhering to the function naming standard of Java and there may be zero or more arguments. When a method is called, it is programmers responsibility to supply the arguments (if it takes any) and accept the return value (if it returns at all). A method always returns back to the caller as soon as it finishes its task.
  User defined function
  Methods can be invoked from Java API library or you may create your own. A method that is created by programmer is called user defined method/function. Some such user defined functions structure may be as follows:
  int calcFactorial(int number) {...} // takes one argument and return int value void setName(String name){...} //takes one argument and returns nothing Object getDateOfBirth(){...} // takes no argument and returns an Object boolean isValid(String userName, String password){...} //takes two argument and returns boolean value – true or false
  static Methods
  As we have seen, every class provides methods that perform common tasks on objects of the class. For example to input data from keyboard, you have called methods on a Scanner object that was initialized in its constructor to obtain input from the standard input (System.in). Although most methods execute in response to method calls on specific objects, this is not the case. Sometimes a method performs a task that does not depend on the contents of any object. Such method applies to the class in which it is declared as a whole and is known as a static method or a class method. To declare a method static, place the keyword static before the return type in the method's declaration. One can call any static method by specifying the name of the class in which the method is declared, followed by a dot(.) and the method name, as in
  ClassName.methodName(arguments)
  e.g. Math.sqrt(32.0);
  For example, you can calculate the square root of 49.0 with the static method call Math.sqrt(49.0).
  Why is main method declared static
  When Java application run, JVM attempts to invoke main method of the class you specify. Declaring main as static allows the JVM to invoke main without creating an instance of the class such as – YourClassName.main. JVM simply seeks for main function inside the classes and tries to execute it to kick start the application.
  Declaring and using methods
  There are three ways to call a method
  - Using method name such as – getName()
  - Using a variable that contains a reference to an object, followed by a dot(.) and the method name to call a method referenced by that object.
  - Using the class name and a dot(.) to call a static method of a class.
  Lets try and example to implement the above type of function call
  import java.util.Scanner; public class MaxFinder { //user defined function public void findMax(){ Scanner input = new Scanner(System.in); double val1 = input.nextDouble();// Java API library function double val2 = input.nextDouble();// for keyboard input double val3 = input.nextDouble();// function called with referenced object - input input.close(); double result = max(val1, val2, val3); // user defined function call System.out.println("Maximum value is: "+ result); } //user defined function public double max(double n1, double n2, double n3){ double maximum = n1; if(n2>maximum) maximum = n2; if(n3>maximum) maximum = n3; return maximum; } //user defined static function public static void doubleRange(){ System.out.println(Double.MIN_VALUE); System.out.println(Double.MAX_VALUE); } }// end of MaxFinder class //------------------------------------------ public class MaxFinderApp { public static void main(String[] args) { MaxFinder maxFinder = new MaxFinder(); maxFinder.findMax(); MaxFinder.doubleRange(); }// end of main } //end of MaxFinderApp class
  Note: static method can call only other static methods of the same class directly and can manipulate only static fields in the same class directly.
  How method call works
  When a program calls a method, the called method must know how to return to its caller, so the return address of the calling method is pushed onto the program execution stack or method call stack. If a series of method call occurs, the successive return addresses are pushed onto the stack in last-in, first-out order so that each method ca return to its caller.
  Note: Stack is a data structure analogous to a pile of books. When a book is placed it is generally placed on the top. Similarly, when a book is removed it is removed from the top of the pile. Thus the structure it follows is last-in, first-out (LIFO) – the last item pushed(placed) on the stack is the first item popped(removed) from the stack.
  Quizzes
  1. A method is invoked with
  (1) a method call
  (2) a stack
  (3) return type
  (4) function signature
  2. A variable known only within the method in which it is declared is called
  (1) global variable
  (2) function variable
  (3) local variable
  (4) variable
  3. The _________ statement in a called method can be used to pass the value back to the calling method
  (1) break
  (2) continue
  (3) return
  (4) void
  4. Which keyword indicate that the method does not return a value
  (1) int
  (2) void
  (3) public
  (4) static
  5. Data can be added or removed only from the __________ of a stack
  (1) bottom
  (2) void
  (3) left side
  (4) none of the above
  6. Stacks are known as which of the following data structure
  (1) FIFO
  (2) LRU
  (3) Tree
  (4) LIFO
  7. static methods are called
  (1) static function
  (2) class method
  (3) main function
  (4) none of the above
  8. double is a primitive ____________
  (1) class
  (2) method
  (3) object
  (4) data type
  9. User defined functions are created by
  (1) Java API Library
  (2) Java Virtual Machine
  (3) Java Application
  (4) programmers
  10. Java application without main declared as static
  (1) will not run
  (2) will not compile
  (3) will run without error
  (4) will neither compile nor run
  11. A static method can only manipulate static fields
  (1) true
  (2) false
  Task: Try yourself
  - Write a program with user defined function that prompts the user for temperature in Fahrenheit and convert it into Celsius. (hint. Celsius = 5.0/9.0 * (Fahrenheit-32);
  - Write a method gcd that return the greatest common divisor of two integers.
  - Modify the MaxFinder program into MinFinder program.
  - Write a method that takes a digit as argument and returns the digits reversed (e.g. 1234 reversed to 4321)
  Previous: Control statements | Next: Arrays | Back to Table of content
  Edited by mdebnath, 08 March 2013 - 01:47 AM.