Introduction

We used methods to divide large and complex programs into small programs that are easier to manage. We can also refer to methods as collection of statements that perform a specific task and they can be void or have a returning value.

  • Void method: a block of statement with no returning value.
  • Value returning method: a block of statement with returning value to the statement that called it.

Instead of writing one large programs with all the statements, we can use methods to break the program into small block of statements and each block solves a specific part of the problem.

Let look at some examples.

This is a long complex program with all the statement in one method.

public class Problem 
{
	public static void main(String[] args)
    {
  	//All the statements here
        statement;
        statement;
        statement;
        statement;
        statement;
        statement;
        statement;
        statement;
        statement;
        statement;
        .
        .
        .
        .
   }
}

The following program has been divided into small parts.

public class Problem
{
    //This is the main method
    public static void main(String[] args)
    {
    	statement;
    	statement;
    	statement;
    }
    
    //Method 1 - This method solves an specifict part of the problem 
    public static void()
    {
    	statement;
        statement;
        statement;
    }
    
    //Method 2 - This method solves another part of the problem
    public static void()
    {
    	statement;
        statement;
        statement;
    }
    
    //Method 3 - This method solved a different part of the problem
    public static void()
    {
    	statement;
        statement;
        statement;
    }
}

Basic program using method.


public class basicMethod {

	public static void main(String[] args) {
	// TODO Auto-generated method stub

	//CALL THE helloTechnikal METHOD
	helloTechnikal();
		
	// PRINT A MESSAGE
	System.out.println("Getting started with methods");
	}

	// CREATE A METHOD THAT DISPLAYS technikal.io
	public static void helloTechnikal()
	{
		System.out.println("Hello, technikal.io");
	}
}

We have covered the basic of methods in Java programming and went over some examples.