Java Methods: Define & Use Guide
In Java, a method is a reusable block of code used to perform a specific task. It defines the method’s name, parameters, return type, and the code to be executed within the method.
Here is an example demonstrating how to define and use a basic Java method:
public class MyClass {
// 定义一个方法,该方法不接受参数并且没有返回值
public void sayHello() {
System.out.println("Hello!");
}
// 定义一个方法,该方法接受两个整数参数并返回它们的和
public int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
MyClass myObj = new MyClass();
myObj.sayHello(); // 调用sayHello()方法,输出 "Hello!"
int result = myObj.addNumbers(5, 3); // 调用addNumbers()方法,传入参数并接收返回值
System.out.println("Sum: " + result); // 输出 "Sum: 8"
}
}
In the above example, we have defined a method called sayHello() that takes no parameters and does not return any value. The code within the method is used to print “Hello!”.
We also defined a method called addNumbers() that takes two integer parameters, a and b, and returns their sum. The code inside the method calculates and returns the sum of the two parameters.
In the main() method, we create an object myObj of MyClass, then we call the sayHello() method and addNumbers() method using the object. The addNumbers() method takes in the parameters 5 and 3, stores the return value in the result variable, and finally outputs the value of result.
This is the basic definition and usage of Java methods. You can define your own methods as needed and call them in the program to perform specific tasks.