Defining methods
- Java course
- Beginner
- Lesson 71/116
- 4 min
Learn to define static methods.
Defining methods
A method is a named block of code that does a specific job. The static keyword defines the method at class level; it can be called directly from main.
static void greet() {
System.out.println("Hello");
}The shape is: static returnType name(parameters) { ... }. When the return type is void, the method returns no value. With no parameters, the parentheses stay empty. To call it, just write the name and the parentheses.
Calling a method and flow
After you define a method, you call it by writing its name and parentheses. When called, the flow jumps into the method and returns when the code finishes.
public static void main(String[] args) {
greet();
greet();
}
static void greet() {
System.out.println("Hello");
}In this example, Hello is printed twice. The method is defined once and called as many times as needed. This prevents code duplication.
Practice Write a greeting method
Define a static void method called greet; its body should run System.out.println("Hoş geldin"). Call it twice from main.
Starter code
public class Main {
public static void main(String[] args) {
// Call the greet method twice
}
// Define the greet method here
}Sample solution
static void greet() {
System.out.println("Hoş geldin");
}
// inside main:
greet();
greet();Expected output
Hoş geldin Hoş geldin
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is a valid static method definition?
- static void greet() { }
- def greet():
- function greet() { }
- void static greet() { } Correct answer
Explanation: In Java, static comes first, then the return type, then the name.
2 Match method part to purpose
| Term | Meaning |
|---|---|
static |
Defines at class level |
void |
Returns no value |
() |
No parameters |
{ } |
Method body |
3 Fill in the blank: call the method
public static void main(String[] args) {
greet____;
}
static void greet() {
System.out.println("Hello");
}
public static void main(String[] args) {
greet();
}
static void greet() {
System.out.println("Hello");
}
Explanation: You called the method with greet().