Methods

Author: Ravi Poswal

Java methods are blocks of code that perform certain tasks. It is a technique of improving efficiency and reuse of code. All Java methods must belong to a class. Methods showing the behavior of an object. Benefits of methods

  • Code Reusability
  • Maintainability
  • Easy Modification
  • Readability 

Methods are two types:

1. System define/predefine 

2. user-defined 

The predefined methods that are already specified in the Java package. It is also referred to as the built-in method or the standard library approach. like that getState(), setState(), println, etc.

Code Example

class A
{ 
public static void main(String ar[])
{
System.out.println("hello");
}
}

2. User-defined method

Programmers write a block of code known as user-defined methods. If a user-defined method is non-static, we must first create an object of the class before calling the method with that object. Method prototypes are not mandatory parts in Java. because Java uses complete method definitions instead of separate declarations.

a. Method Calling

b. Method Definition/Body

Code Example

class Ranrev {
    void ab()   // method definition
{
        System.out.println("This is a user-defined method in ranrev");
    }

    public static void main(String[] args) {
        Ranrev obj = new Ranrev(); 
        obj.ab();             // method calling
    }
}

FAQs

Access Modifier – defines visibility (public, private)
Return Type – type of value returned (int, void)
Method Name – identifier of method
Parameter List – inputs to method
Method Body – logic inside { }
Return Statement – sends value back

Predefined
println() //method
user defined
ranrev() // user defined method