HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Java Methods

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

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

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:



Inside main, call the myMethod() method:

Example
              
             
public class Main {
  static void myMethod() {
    System.out.println( "I just got Coding!");
  
  public static void main(String[] args) {
    myMethod();
  }
}

// Outputs "I just got Coding!"