Java Methods: Reusable Blocks of Code for Efficient Programming

Learn about Java methods, which are blocks of code designed to perform specific actions when called. Methods can accept parameters and help in code reuse by allowing you to define functionality once and call it multiple times. Explore how to create custom methods in Java and understand the importance of pre-defined methods like System.out.println().



Java Methods

A method in Java is a block of code that executes when it is called. Methods can accept data called parameters and are used to perform specific actions, often referred to as functions.

Why use methods? Methods allow you to reuse code by defining it once and using it many times.

Create a Method

To create a method in Java, you must declare it within a class. It is defined with a name followed by parentheses (). Java includes pre-defined methods like System.out.println(), but you can create your own methods:

Syntax

public class Main {
static void myMethod() {
// code to be executed
}
}

Example Explained

  • myMethod() is the name of the method.
  • static indicates that the method belongs to the Main class and not an instance of the class.
  • void specifies that this method does not return a value.

Call a Method

To call a method in Java, simply write its name followed by parentheses () and a semicolon. Here's an example of calling myMethod() inside the main method:

Example

public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {
myMethod();
}
}
Output

I just got executed!

Calling a Method Multiple Times

A method can be called multiple times from within the program. Here's an example:

Example

public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
Output

I just got executed!
I just got executed!
I just got executed!

Explanation: Each time myMethod() is called within main(), it executes the code inside it, printing "I just got executed!" to the console.