Java Tutorials
Java Methods
Java Classes
Java File Handling
The method is a code block that only works when called.
You can transfer data, known as parameters, into a method.
Methods are used to perform certain actions, and are also known as functions.
Why should you use methods? Code reset: define code once, and use it multiple times.
The method must be announced in class. Defined by the path, followed by parentheses (). Java offers pre-defined methods, such as System.out.println()
, but you can also create your own custom actions:
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
myMethod()
the method namestatic
means that the method belongs to the Main category and not to the Main category.You will learn more about objects and how to access methods by using objects later in this lesson.void
means that this method has no return value. You will learn more about recovery values later in this chapterTo drive a path in Java, type the path path followed by two parentheses () and a semicolon ;
In the following example, myMethod()
is used to print text (action), if it is called:
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!"
The method can also be called multiple times:
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!