Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -


  • Please log in to reply
5 replies to this topic

#1 mdebnath


    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 17 February 2013 - 02:06 AM

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


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

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

  1. Using method name such as – getName()
  2. 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.
  3. 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
        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;
            maximum = n2;
            maximum = n3;
        return maximum;
    //user defined static function
    public static void doubleRange(){
}// end of MaxFinder class

public class MaxFinderApp {
    public static void main(String[] args) {
        MaxFinder maxFinder = new MaxFinder();
    }// 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.




 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.

  • 0

#2 bagofmilk


    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 13 March 2013 - 06:43 AM

When do we use a private function as opposed to a public function. I've also see protected functions, can someone explain the differences?

  • 0

#3 KodeKool


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 276 posts
  • Location:Ontario Canada
  • Programming Language:C, Java, C++, C#, PHP, JavaScript, Transact-SQL, ActionScript, Others
  • Learning:Python, Perl, Ruby, Lua

Posted 13 March 2013 - 08:40 AM

private functions are class specific functions that shouldn't be accessed outside of their home class, the private access modifier is normally used for member variables such as for example in a clock class, you might have the member variables hourHand, minuteHand, and secondHand all set to private, this is because your hands shouldn't be accessed outside of the clock. however to access them you would use your accessor and modifier methods (getters and setters) to access the values of the member variables. 


The protected access modifier allows what it is applied to to be used within the package, meaning any class within the package can access protected, but anything outside of the package cannot. 


so just to specify all three:


Public: allows access in all scopes: class, package, and outside the package.

Protected: allows access only to the class and the package.

Private: allows access only to the class it's declared in.


Hope this helps :)

  • 0

~A program will always do what you tell it to do, and seldom what you want it to do~

Check out my latest PHP tutorial

#4 XB23


    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 04 July 2014 - 08:54 AM

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.



I didn't understand this. How would it create an instance of the class if we didn't declare main as static?

  • 0

#5 Ritwik I the programmer

Ritwik I the programmer

    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 244 posts
  • Programming Language:Java
  • Learning:Java, C++, Python

Posted 04 July 2014 - 10:22 PM

JVM would not, by itself, specifically create an instance of any class unless the code written by the programmer tells it to(at least, not any instances that you need to bother about). A main() function, if not static, would be regarded as just another method, not THE main() function from which execution of a program starts.

  • 0

I can believe, but why should I?

#6 XB23


    CC Newcomer

  • Member
  • PipPip
  • 22 posts

Posted 05 July 2014 - 05:11 AM


  • 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download