[go: up one dir, main page]

0% found this document useful (0 votes)
46 views2 pages

You Can Pass Data

Methods allow code to be reused by defining actions once that can then be called many times. A method must be declared within a class and is defined with a name and parentheses. To call a method, write its name and parentheses and use it to perform an action like printing text. Methods can be called multiple times.

Uploaded by

rent mark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views2 pages

You Can Pass Data

Methods allow code to be reused by defining actions once that can then be called many times. A method must be declared within a class and is defined with a name and parentheses. To call a method, write its name and parentheses and use it to perform an action like printing text. Methods can be called multiple times.

Uploaded by

rent mark
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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
Create a method inside MyClass:

public class MyClass {


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

Example Explained
 myMethod() is the name of the method
 static means that the method belongs to the MyClass class and not
an object of the MyClass 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:

Example
Inside main, call the myMethod() method:

public class MyClass {


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

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"

Run example »

A method can also be called multiple times:

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

public static void main(String[] args) {


myMethod();
myMethod();

You might also like