Java Basics-Method

Source: Internet
Author: User
Tags define function modifier modifiers

Method

in our daily life, we will encounter a variety of problems, and we need to find solutions to these problems, that is, solutions, so the methods are ubiquitous in daily life. In Java , we solve a problem and find a solution to this problem is the method. The method encapsulates the functionality of the specific code implementation that solves the problem, and we just need to call this method name to solve the problem. The call to the random number, as previously learned, is called the Nextint () method to implement the random number generation.

To define the format of a method:

modifier return value type Method Name ( parameter list ...) {

specific code for the implementation of the feature

Return

}

Method Format Analysis:

modifiers: Used to decorate the various states of the method, modifiers are more, now first fixed, the meeting will gradually contact,public static,the public permission modifier, maximum permissions,static , Static, is also the meaning of data sharing.

Return value type: The method implementation function returns the result of the data type, returning the result of what type is written.

Method Name: The definition of a method name follows the rules for identifiers, the first word is lowercase, and the first letter of each word is capitalized.

Parameter list: whether there is an unknown data participation, not defined

Return: There are two functions, one is to return the result of this function, and the other is to end the method.

Here's a code to demonstrate the specifics of the method definition:

/* Requirements: Calculate the area of the rectangle (implement this function in the method) idea: 1, define a method Getarea () implement in the method             2, modifiers: public static           3, Return value type: Calculates the area of the rectangle returned after the value of an integer type, int           4, Method Name: Follows the definition of the identifier Rule getarea ()            5, parameter list: In the function implementation process, There are unknown data involved in the operation, long and wide,int length,int weight            6, return is the area.            7, invokes the function of the method, and invokes it in the Main method */public class  methoddemo{         public static void main ( String[] args) {                    //Call the Getarea () method, passing in long and wide values                &nbsP;    int area = getarea (4,8);                    //Print the value of the area                     system.out.println (" The area of the rectangle is: "+area);         }          //define the method, implement the function of the package          public static  Int getarea (int length,int weight) {                    //function Realization of computing area                     //int area = length  * weight;                    return length * weight;         }} 
method Definition ExercisesExercise One: Print three rows of three columns“*”Rectangle
/* Requirements: Print three rows and three columns of "*" Rectangle idea: 1, define function method            2, modifier: public  static           3, return value type: Print graphics in the console can be   There is no return value type Void           4, method name: A definition rule that conforms to an identifier, Printrect ()            5, parameter list: Already specified is three rows three columns, do not need to define the parameter list */public  Class methoddemo_1{         public static void  main (String[] args) {                    //Invoke Function Method                     printrect ();          }         //Defining functional Methods           public static&nbsP;void printrect () {                    //using a For loop to traverse the print rectangle                     for (int i=0;i<3;i++) {                              for (int j=0;j<3;j++) {                                       system.out.print ("*");                              }                &nbsP;            system.out.println ();                    }          }}
exercise two: Keyboard enter a number and print this number
/* Requirements: Keyboard Enter a number and print this number idea: 1, define the function method            2, modifier: public  static           3, return value type: The number of inputs that need to be returned,int            4, method name: Follow the definition rules of identifiers, GetNumber ()             5, parameter list: No unknown data participation, just need to enter this number on the keyboard to */import  java.util.scanner;public class methoddemo_2{          Public static void main (String[] args) {                    //Invoke Function Method                     //int num =  GetNumber ();                    system.out.println (GetNumber ());         }          //Defining method Functions          public static int getnumber () {                    //define scanner class, complete keyboard input                     scanner sc = new scanner (System.in);                    //int  Number = sc.nextint ();                    //returns the input data to the caller                     return sc.nextint ();          }} 
Exercise Three: print the specifiedMrow, per lineNa*Number of rectangles
/* Requirements: Print a rectangle of the specified m line with n * Numbers per line: 1, define the function method            2, modifier: public  static           3, return value type: Print graphics, no return value void            4, method name: conforms to the definition rules of identifiers, Printrect ()             5, parameter list: You need to specify the number of rows and columns of the graph,int m,int n            6, calling function method */public class methoddemo_3{          public static void main (String[] args) {                    // Calling function Methods                     printrect (6,7);         }          Defines the function method          public static void printrect (int  m,int n) {                    //traversing a print graphic with a For loop                     for (int i=0;i<m;i++) {                              for (int j=0;j<n;j++) {                                       system.out.print ("*");                              }                             system.out.println ();                    }          }}
exercise four: averaging three numbers
/* Demand: Three number of average ideas: 1, define functional methods            2, modifier:public  Static           3, return value type: The average result needs to return the value of the average of these three numbers,int            4, method name: conforms to the definition rules of identifiers, Getavg ()             5, parameter list: Requires participation of three unknown data,int a,int b,int c            6, calling function method */public class methoddemo_4{          public static void main (String[]  args) {                    //Invoke Function Method                     int avg = getavg (4,8,9);                    system.out.println (the average of three numbers is: "+avg);          }         //Defining functional Methods           public static int getavg (int a,int b,int c) {                    // Returns the calculated value                     return  (A+b+c)/3;         }}
Some considerations when defining a method:

1, methods written in the class, methods and methods can not be nested, that is, one method can not be written into another method,

2. the method name and argument list must not be written incorrectly when calling the method, otherwise the failure

3, The return value of the method if it is Void,ruturn can omit to write, but the method of return must not be written after the other statements, otherwise it will not be able to access the compilation failed

4. The return value type of the method must match the type of return .

5, the method can not be repeated definition.

6, when calling the method, the return value of the method is void, the call can not use the output statement, no return value printing data is not present, logic error.

Overloading of methods

The so-called overload is in the same class, the function of the method name can be the same, but its parameter list of the data type and the number of data is different.

The following code demonstrates the case of overloading:

/* Overloaded Case: The number and type of data are not determined, so heavy load */public class methodoverload{       is required.    public static void main (String[] args) {                    //Invoke function                     int sum1  = add (3,5);                    int sum2 = add (4,5,6);                    double sum3 = add ( 2.1,6.3);                    system.out.println (SUM1);                     system.out.println (sum2);                    system.out.println (SUM3);          }         //function Realization of summation           public static int add (int a,int b) {                    return a+b;          }          Public static int add (int a,int b,int c) {                    return a+b+c;          }         public  Static double add (DOUBLE&NBSP;A,DOUBLE&NBSP;B) {                    return a+b;         }}
Considerations for Overloading

1. The parameter list of the method must be different (number of data, data type, data order)

2. overloading of methods is independent of variable names

3. overloads of the method are independent of the return value type

4. method overloads and modifiers are irrelevant

So the overloads of the method are only related to the argument list, and other irrelevant


Java Basics-Method

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.