Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Java Methods


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.


Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:


Example

Get your own Java ServerCreate a method inside Main:

        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:

Example

Inside main, call the myMethod() 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 also be called multiple times:

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!
       


Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java