bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Methods
Java•Java Methods

Java Methods

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Methods?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

public ___ Main {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Methods are used to perform certain actions, and they are also known as functions .
You can pass data, known as parameters, into a method.
A method is a block of code which only runs when it is called.

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:

Create a method inside Main

public class Main {
 static void myMethod() {
 // code to be executed
 }
}
  • myMethod() is the name of the method
  • static means that the method belongs to the Main class and not an object of the Main class. You will learn more about objects and how to access methods through objects later in this tutorial.
  • void means that this method does not have a return value. You will learn more about return values later in this chapter

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:

main

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!

In the next chapter, Method Parameters , you will learn how to pass data (parameters) into a method.

Next

Java Method Parameters