What Is Method?

In this lecture, we are going to talk about how important methods are for us in java programming.

Method

A method is a block of code or a collection of statements to perform a certain task or operation. We can pass data through the method parameter. It’s used for the reusability of code. In methods, we define code once and use it many times. A method is also known as a function. Mostly it provides easy modification and readability of code. The methods and functions always run when it’s called.

Method Signature

Access Specifier

An access specifier or modifier is an access type of function and method. The modifiers specify the visibility of the method. In java, we have four types of access specifiers.

  • Public
  • Private
  • Protected
  • Default
  1. Public – When we use public access specifier, the method is accessible in all classes.
  2. Private – When we use a private access specifier, the method is accessible within the declared class.
  3. Protected – When we use a protected access specifier, it works like an inheritance. the method is accessible within the same package or subclasses of different packages.
  4. Default – When we do not use any of the above access specifiers while method declaration, java set your method default specifier which is accessible in the same package only.

Creating Method

The methods are always declared in the class. The method name is always followed by parentheses (). Java has some pre-defined methods, for printing and displaying variables such as System.out.println(). We also create our own custom methods.

public void add(){
 int x = 50;
 int y = 70;
 int z = x+y;
 System.out.println("the addition value of x+y is: " + z );
}

 

We created our custom add() method, now it’s time to get that method in our main method.

public class Main {
    
    public void add(){
        int x = 50;
        int y = 70;
        int z = x+y;
        System.out.println("the addition value of x+y is: " + z );
    }

   public static void main(String[] args) {
        Main m = new Main();
        m.add();
   }

}

 

We use the void return type above, which means no return value. Now we create the same method but in a different return type method that returns some values.

public class Main {

    public int add(){
        int x = 30;
        int y = 70;
        int z = x+y;
        System.out.println("the addition value of x+y is: " + z );
        return z;
    }

   public static void main(String[] args) {
        Main m = new Main();
        m.add();
   }
}

 

#BeingCodeStuffer

Related Java Programmings