Table of Contents
Methods, sometimes called functions, are blocks or sections of code, usually named, that can be executed over and over again. methods are great for reducing duplication of code, improving readability, and reducing complexity. Divide up larger chunks of code so that they become easier to manage.
Creating a method
Let's look at a method that simply prints out a greeting:
JAVApublic static void introduction() {
System.out.println("Hello, my name is Jackie.");
}
You can ignore what public
and static
means for now. The important part to take away is the return type is void
. Methods can return things back to you, like a String
or int
, but in this case, we are only printing some text, so we can set the method to return nothing.
Finally we just have the actual code that is being run, the print statement.
Invoking a method
Now that we have defined our method, we just need to invoke or call it. This causes the method to execute:
JAVApublic class Main {
public static void main(String[] args) {
introduction();
}
public static void introduction() {
System.out.println("Hello, my name is Jackie.");
}
}
BASHHello, my name is Jackie.
This is cool and all, but what if you wanted to customize the name instead of it being hardcoded?
Parameters
Parameters are pieces of data you can pass into a method that you can then use to perform that method's task. In this case, we want to customize the name that appears, so let's add the name as a parameter:
JAVApublic class Main {
public static void main(String[] args) {
introduction("Nia");
}
public static void introduction(String name) {
System.out.println("Hello, my name is " + name + ".");
}
}
BASHHello, my name is Nia.
Return Values
As mentioned before, methods can optionally return something back to you. In Java, void
makes it so that it returns nothing, but setting it with a type makes it return that type.
Let's look at the getting the area of a triangle:
JAVApublic class Main {
public static void main(String[] args) {
int sideLength = 3;
int area = getAreaOfSquare(sideLength);
System.out.println(area);
}
public static int getAreaOfSquare(int side) {
return side * side;
}
}
BASH9
We created a method called getAreaOfSquare()
that takes the side length of a square. It then calculates the area and returns it as an int
. Now we use that value to set the value of the variable named area
which we then print out.
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to deploy a PHP app using Docker
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API