Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Methods

Java Methods

A method is a segment of code that executes solely upon invocation.

Data, referred to as parameters, can be passed into a method.

Methods, also termed as functions, are employed to execute specific actions.

The primary purpose of using methods is to enable code reuse: defining functionality once and utilizing it multiple times.

Create a Method

In Java, a method must be enclosed within a class. It is characterized by its name followed by parentheses (). While Java offers pre-defined methods like System.out.println(), you also have the flexibility to define your own methods for executing specific actions.

Example

Generate a method within the Main class.

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

Example Explained

  • The method is named myMethod().
  • The keyword static indicates that the method belongs to the Main class rather than an instance of the Main class. More about objects and accessing methods through objects will be covered later in this tutorial.
  • The keyword void signifies that the method does not return any value. Further explanation about return values will be provided later in this chapter.

Call a Method

To invoke a method in Java, simply write the method’s name followed by a pair of parentheses ( ) and a semicolon.

In the given example, the method myMethod() is utilized to print a text (the action) whenever it is invoked.

Example

Invoke the myMethod() method within the main method.

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

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

// Outputs "I just got executed!"

A method can be invoked multiple times as well:

Example

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

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

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

 

In the upcoming chapter, Method Parameters, you’ll explore how to transmit data (parameters) into a method.