Methods in Java

Source: Internet
Author: User

How to define methods in Java (i)

The so-called method, which is used to solve a class of problems, is an orderly combination of code, is a functional module.

In general, the syntax for defining a method is:

which

1, Access modifier: The method allows access to the scope of the permission, can be public, protected, private can even omit, where public means that the method can be called by any other code, the use of several other modifiers in the later chapters will explain in detail the drop

2, return value type: The type of the return value of the method, if the method does not return any value, the return value type is specified as void, if the method has a return value, you need to specify the type of the return value, and return the value in the method body using the return statement

3. Method Name: The name of the method defined, must use a valid identifier

4. Parameter list: Parameter list passed to method, parameter can have multiple, multiple parameters separated by commas, each parameter consists of parameter type and parameter name, separated by space

The method can be divided into four classes depending on whether the method has parameters or not, and whether it has a return value:

    • ? No parameter no return value method

    • ? Non-parametric return value method

    • ? No return value method with parameter

    • ? Return value method with a parameter

 Public classHelloWorld {//Defines a method named print to implement the output information function     Public void Print() {System. out. println ("Hello World"); } Public void Print1() {System. out. println ("I love you."); } Public void Output() {System. out. println ("I Love You"); } Public Static void Main(string[] args) {//Call the Print method in the Main methodHelloWorld test=NewHelloWorld ();         Test.print (); HelloWorld test1=NewHelloWorld ();               Test1.print1 (); HelloWorld test2=NewHelloWorld ();    Test2.output (); }}
No parameter no return value method

If the method does not contain a parameter, and there is no return value, we call it a method without parameters and no return value.
The use of the method is in two steps:

The first step is to define the method

For example, the following code defines a method named show with no parameters and no return value, and the operation is output "Welcome to IMOOC."

Attention, OH:

1, the method body is placed in a pair of curly braces, to achieve a specific operation

2, the method name is mainly used in calling this method, you need to pay attention to the naming of the specification, generally use the first letter lowercase, other words capitalized form

The second step is to invoke the method

When you need to invoke a method to perform an action, you can first create an object of the class, and then pass the object name. Method name (); to implement (the concept of classes and objects in the later chapters will be explained in detail, first familiar with grammar, table anxious Oh ~ ~)

For example: In the following code, we create an object named Hello, and then output the information by calling the show () method of the object

Full code
publicclass HelloWorld {    publicstaticvoidmain(String[] args) {        // 创建对象,对象名为hello        HelloWorld hello =new HelloWorld();                   // 调用方法        hello.showMyLove();    }    /*     * 定义无参无返回值的方法     */    public   void    showMyLove() {        System.out.println("我爱慕课网!");    }}
Non-parametric return value method

If the method does not contain a parameter, but has a return value, we call it a method with no parameter return value.

For example: The following code, which defines a method named Calsum, has no arguments, but the return value is of type int, performs an operation that calculates the sum of two numbers and returns the result

In the Calsum () method, the return value type is type int, so you must return an integer value using return in the method body.

When calling a method with a return value, it is important to note that because the method executes returns a result, the return value is generally received and processed when the return value method is called. Such as:

The result of the operation is: two sum of: 17

"Small traps" that cannot be overlooked:

1. If the return type of the method is void, the return value cannot be used in the method!

2. The return value of a method can have at most one and cannot return multiple values

3, the type of the method return value must be compatible, for example, if the return value type is int, you cannot return a String value

 Public classHelloWorld { Public Static void Main(string[] args) {//Create an object named HelloHelloWorld Hello =NewHelloWorld ();//Call the Calcavg () method of the Hello object and save the return value in the variable avg        DoubleAvg = Hello.calcavg (); System. out. println ("Average score is:"+ avg); }//Define a method with a return value of type double     Public  Double   Calcavg() {Doublejava =92.5;Doublephp =83.0;DoubleAvg = (java + PHP)/2.0;//Calculate average        //return value with return        returnAvg }}

Methods in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.