BCA / B.Tech 11 min read

Method Types in Java

Types of Methods in Java

A method is a block of code that runs only when it is called. It is used to perform a specific action and is a fundamental part of organizing code into reusable units. Methods in Java can be categorized in different ways.

1. Based on Definition Source:
  • Predefined/Standard Library Methods: These methods are built into the Java language and are available through the Java Class Library (API). You don't need to write them, just call them. Examples include System.out.println(), Math.max(), and String.length().
  • User-Defined Methods: These are methods created by the programmer to perform custom tasks specific to their application.

2. Based on the `static` Keyword:

This is the most important distinction for user-defined methods.

  • Instance Methods:
    • Belong to an instance (object) of a class.
    • Must be called on a specific object.
    • Can access both instance variables and static variables of the class.
    • Example:
      class Dog {
          String name;
          public void bark() { // Instance method
              System.out.println(name + " says Woof!");
          }
      }
      Dog myDog = new Dog();
      myDog.name = "Buddy";
      myDog.bark(); // Called on the `myDog` object.
                              
  • Static Methods:
    • Belong to the class itself, not any individual object.
    • Called using the class name.
    • Cannot access instance variables directly (as they belong to objects). They can only access static variables.
    • Example:
      class Calculator {
          public static int add(int a, int b) { // Static method
              return a + b;
          }
      }
      int sum = Calculator.add(5, 10); // Called on the `Calculator` class.