More on methods

You have been working with the main method so far. Main method is a special type of method. Every stand alone program must have a main method to help us run from the command line using java executable.


What is a method in general?

A method is a set of statements grouped together and given a name. Program of execution jumps to a method when that method's name is invoked (a.k.a. called).

Who invokes the main method?

  • Main method is invoked by the JRE when you execute java on the program containing the main method.

However all others methods are invoked by main method or another method of the same or different class.

Parts of a method

Along with the method name, a method may contain optional modifiers like public, static etc., optional return type or void if it is not returning anything and optional comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.

Method Names

  • The rules for creating variable names are similar to rules for creating identifiers. However as per the standard naming conventions, method names should start with a small case.

  • Methods denote an action being performed and hence the name should be of a verb form. This is again as per the naming conventions.

Multiple Methods Example

Let us add another method called displayGreetings to our Tutorial program from Chapter 1:

public class Tutorial{
   public static void main(String[] args){
       System.out.println("Good bye");
   public static void displayGreetings(){
       System.out.println("Have a good day!");

In this method, we used public and static modifiers, void return type and empty list of parameters. You invoke the method by keying in the name and parameters in between parentheses. Since this method does not take any parameters, you see nothing between left and right parentheses.

image alt text

The program of execution starts from line number 5, the start of the main method and executes the statement at line number 7. After executing line 7, it moves to line 8 statement which invokes the displayGreetings() method. So now the program of execution jumps inside of the displayGreetings method and executes the System.out.println statement which prints out "Have a good day" and then comes back to where it left off in main method and proceeds to execute the next statement which is System.out.println(“Good bye”) in line number 9.

So to recap, in the above diagram, the program of execution jumps from main method to displayGreetings method at line number 8 to line number 12 and after the method statement is executed, the program of execution jumps back to line number 9 and then finishes the program.

Output of this program would be

image alt text

In the above program the method displayGreetings is defined in line number 12. The defined method is invoked by the main method in line number 8. We have to add the static keyword for the displayGreetings method, otherwise the main method will not be able to invoke this method. Adding public keyword is optional in this example. You will learn more on static and public keywords later. For now it is sufficient to understand this property.

Methods - Points to note

  • A method can declare zero or more input parameters but when it comes to returning, it can only return at most one value.
  • If a method does not return anything then you have to mention void as the return type.
  • A method can be defined anywhere inside the class for it to be invoked from other methods. It is not necessary for the method definition to come first before it is invoked, in Java.
  • A static method can only invoke another static method of the class. Since the main method is static, we have added the static keyword for the methods invoked from main

Example of a Method which Returns a Value

Now let us see another example where you can send a value to a method and also get another value as a return type from the method. We will use an int variable. Although you will learn more on Data Types in the next chapter, for now it is sufficient to understand that int is a data type used to represent integers.

public class NumberDoubler{
   public static void main(String[] args){
       int doubledNumber = doubleTheNumber(10);
       System.out.println("doubled number is " + doubledNumber);
   public static int doubleTheNumber(int a){
       System.out.println("received number:" + a + ". doubling it now..");
       return 2 * a;

Note that 'int a' is being added as a parameter for doubleTheNumber method and void is replaced by int as the return type for the method. The method doubleTheNumber is called from the main method with an argument value of 10 for parameter 'a' declared in the method. The doubleTheNumber method is returning the doubled value using the return keyword used in the second statement of the method. The returned value from the doubleTheNumber method is saved in a variable named doubledNumber in the main method.

Example of a method which takes multiple input values

In the below example the addTwoNumbers method is defined with two parameters; a and b. This method is invoked by sending in the two arguments 10 and 16 in the main method.

public class Addition{
   public static void main(String[] args){
       int sum = addTwoNumbers(10, 16);
       System.out.println("sum is " + doubledNumber);
   public static int addTwoNumbers(int a, int b){
       return a + b;

Why should you add methods?

Methods help compartmentalize your code. You typically write new methods when:

  • Number of code statements in a method exceeds 25 to 30. Then you should think of ways and means in which you can pull out some statements which work together, to solve a specific part of your logic, as a separate method.
  • A block of code is repeating across many parts of your program. Then also the repeating code should be pulled out as a method and replaced with a method invocation.

The above steps are called re-factoring your code. Every good programming refactors their code multiple times to ensure that their code is understandable by others. Your code should like a story, which is easy to read and understand by not just you but any other programmer who looks at your code.

Recap: A method declaration should have five components, in order:

  1. Optional modifiers—such as public, static and others you will learn about later.

  2. Mandatory return type—the data type of the value returned by the method, or void if the method does not return a value. You will learn more about return types going forward.

  3. Mandatory method name— give any name of the verb form and follow java literal naming conventions.

  4. Optional list of parameter in parenthesis; a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.

  5. Mandatory method body, containing optional statements enclosed between left and right curly braces which forms the method code block.

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and statements if any between braces, {}.

results matching ""

    No results matching ""