In java, functions are treated as methods. Other programming languages like C functions are basically a block of statements. Functions are designed to getting same work done by calling it each time.

Why does we used methods in java?

  • Reusable code – method are basically a block of statements. When we calling a method, then we also calls that statements which defines under method (function).
  • Less space – when we calling any method, then that method does the same job each and every time whatever statements declares within that method. So technically it takes less space in program.
  • Save time – time matters for every programmer and developers. Using a method it saves a lot of time.

Let’s discuss about method declaration and calling it…

Creating a method

Let’s assume we have create a class called ‘main’. We can create any method inside ‘main’ class.

Creating a method

class main{

staticvoid method1(){// statements}

}

From the above code example, you see we create a method ‘method1’.

But here you need to familiar with some keywords used in upper code.

  • static – it means ‘method1’ method belongs to main class.
  • void – ‘method1’ method does not have any return type.
  • main – this is base class for now. ‘main’ method class name and java file name should be same.

Calling a method

We calls any method inside ‘main’ method. For calling a method, we need to declare by its name and followed by pair of parenthesis.

class main{
static void method1(){ // statements }
public static void main(String[] args) {
/* called method -> method1()
Calling method -> ‘main’
*/
method1();
}
}

Let’s see some coding example…

public class code1 {
    // defining func1() method
    static void func1(){
System.out.println(“simple method!!”);
    }
    public static void main(String[] args) {
        // calls func1() method
        func1();
    }
}
output

Remember: we call any method ‘n’ number of times.

Let’s see another code below…

public class code2 {
    public static void main(String[] args) {
      // calling msg() nethod 3 times.
msg();
msg();
msg();
    }
    static void msg(){
System.out.println(“welcome to microcodes.in”);
System.out.println(“this is shimanta das.”);
    }
}
output