Home >Java >javaTutorial >How to write Java methods

How to write Java methods

(*-*)浩
(*-*)浩Original
2019-05-31 13:21:008098browse

When we learn operators, we create a new class and main method for each operator separately. We will find that writing code in this way is very cumbersome and there are too many repeated codes. Whether you can avoid these repeated codes requires methods to achieve it.

How to write Java methods

Method: It is to extract a function and define the code separately within a curly bracket to form a separate function.

Definition method, the format is as follows:

修饰符 返回值类型 方法名 (参数列表){
     代码...        
}

Definition format explanation:

Modifier: The current fixed writing method is public static.

Return value type: Currently the fixed writing method is void. Other return value types will be explained in later courses.

Method name: Name the method we define, meet the identifier specifications, and be used to call the method.

Parameter list: The corresponding parameters passed in are used to execute the code function.

Example:

public static void methodName() {
   System.out.println("这是一个方法");  
}

Calling method

After the method is defined, the method will not run by itself and must be called To execute, we can call our own defined method in the main method main. In the main method, just write the name of the method to be called and you can call it.

public static void main(String[] args) {
    //调用定义的方法method
    method();
}
//定义方法,被main方法调用
public static void method() {
   System.out.println("自己定义的方法,需要被main调用运行");  
}

The above is the detailed content of How to write Java methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn