DEV Community

Dinesh G
Dinesh G

Posted on

Methods in Java

What is methods in java

Method :

  • A method is a block of code that performs a specific task and declared within the class. Methods are fundamental to object-oriented programming in Java, as they encapsulate the behavior of objects.
  • Set of instructions for achieving a specific-tasks - with a name (or) with or without arguments (or) with or without return datatype.
  • If we do not return any value, we should mention void before method name.
  • Modularity
  • Code Reusability

employee1.enquiry();
employee1.enquiry(1234);
}

private void enquiry(int accNo) {
    System.out.println("Balance enquiry");

}

private void enquiry() {
    System.out.println("General enquiry");

}
Enter fullscreen mode Exit fullscreen mode

Same method name with different number of arguments is called Method overloading.

employee1.enquiry(15.3f);
private void enquiry(float gold) {
System.out.println("Gold rate please");
}

Same method name with different type of arguments is also known as Method overloading.

Another name called Compile time polymorphism.

Types of Methods:

  • User-Defined Methods: Created by the programmer to perform custom tasks.
  • Standard Library Methods: Predefined methods provided by Java's API (e.g., System.out.println()).

Why use methods?

  • Code Reusability: Define code once and call it multiple times.
  • Modularity: Break down complex programs into smaller, manageable units.
  • Readability and Maintainability: Improve code structure and make it easier to understand and debug

Top comments (0)