Methods and Arrays of Java

Source: Internet
Author: User

Method

1. Overview of methods

Suppose there is a game program, the program in the process of running, to constantly launch shells. The firing of shells requires writing 100 lines of code, and each time we implement the firing shells we need to write the 100 lines of code repeatedly, so the program becomes very bloated and less readable. In order to solve the problem of code duplication, you can extract the code of the firing shells and put them in a {}, and give the code block a name, so that each time the firing of shells by this name to invoke the code to launch the shells. In the above process, the extracted code can be considered as a method defined in the program, the program in the need to fire shells where the method can be called.


2. Definition and format of the method

Method definition: Simply put, the method is a block of code that accomplishes a particular function. In many languages there are definitions of functions, and functions are called methods in Java.

Format of the method:

The access modifier returns a value type method name (argument type parameter name 1, argument type parameter name 2,...    ) {function body; return value;}

So what if we write a method? 1. Return value type the data type of the result of the explicit function 2. The parameter list explicitly has several parameters, and the type of the parameter

public int Add (int a,int b) {return a + B;}


3. Method calls with a definite return value

The invocation of a method with a definite return value, if it is called alone, has no meaning; if it is an output call, it is meaningful, but not good enough, because I do not necessarily output the result, if it is an assignment call, the recommended way.

/** *  for two numbers and  */public class methoddemo1 {     public static void main (String[] args) {         //call         //add alone (;   ) The      //output calls         //system.out.println (Add ( ));         //Assignment Call          Int sum = add,         system.out.println ("Sum of two" + sum);     }    public static int add (int a , INT B) {        return a + b;     }} 
import java.util.scanner;/** *  keyboard input Two data, return two number of maximum value  */public class methoddemo1  {    public static void main (String[] args) {         scanner input  = new scanner (System.in);         system.out.println ("Please enter First Data:");         int num1 = input.nextint ();         System.out.println ("Please enter a second data:");        int num2 =  Input.nextint ();         system.out.printf ("Maximum" +getMax (num1,num2));     }    public static int getmax (Int a ,int  B) {        return a > b ? a :  b;    }}
import java.util.scanner;/** *  keyboard input Two data, compare two data is equal  */PUBLIC CLASS METHODDEMO1  {    public static void main (String[] args) {         scanner input  = new scanner (System.in);         system.out.println ("Please enter First Data:");         int num1 = input.nextint ();         System.out.println ("Please enter a second data:");        int num2 =  Input.nextint ();         boolean flag = isequals (NUM1, NUM2);         if (flag) {             system.out.println ("Two data equal");         } Else{      &nbsP;     system.out.println ("Two data Not equal");         }    }    public static boolean isequals (Int a  ,INT B) {        return a == b;     }}
import java.util.scanner;/** *  keyboard Input 3 data, find the maximum value in 3 numbers  */public class methoddemo1  {    public static void main (String[] args) {         scanner input  = new scanner (System.in);         system.out.println ("Please enter First Data:");         int num1 = input.nextint ();         System.out.println ("Please enter a second data:");        int num2 =  Input.nextint ();         system.out.println ("Please enter a third data:");         int num3 = input.nextint ();         SYSTEM.OUT.PRINTLN ("Maximum value is" +getmax (num1,num2,num3));    }     public static int Getmax (int a ,int b,int c) {        return  (a  > B)? (A>C?A:C):(b>c?b:c);     }}


4. Considerations for Methods

method does not call do not execute

Methods and methods are peer relationships and cannot be nested defined

The parameters are separated by commas when the method is defined

No more data types are passed when the method is called


5. Practice

/** *  demand, in console output such as Shape  *  ***** *  ***** *  ***** *   ***** */public class methoddemo2 {    public static  void main (String[] args) {        printxing (4,5);     }    public static void printxing (int m,int n) {         for  (int x = 0 ; x <  m ; x++ ) {            for   (int y = 0 ; y < n ; y++ ) {                 system.out.print ("*");             }             systeM.out.println ();         }    }} 

/** *  requirements in console output such as Shape  *   output 99 multiplication table  */public class MethodDemo2 {     public static void main (String[] args) {      &NBSP;&NBSP;&NBSP;PRINTNN (9);     }    public static void &NBSP;PRINTNN (int n) {        for  (int x = 1  ; x <= n ; x++) {             for  (int y = 1; y <= x; y++) {                 system.out.print (y+ "*" +x+ "=" +y*x+ "\ T") ;            }             system.out.println ();         }     }}

6. Invocation of a method without an explicit return value

is actually called by the Void type method, and can only be called separately.


7. Method overloading

Method Overloading Overview: In the same class, more than one method of the same name is allowed, as long as they have a different number of arguments or parameter types.

Method overloading features: 1. Regardless of the return value type, look only at the method name and the parameter List 2. At invocation time, the virtual machine distinguishes the method with the same name by different argument lists

/** *   Method Overloading  */public class overloaddemo {    public  static void main (String[] args) {         System.out.println ("Sum of two numbers:" +sum);         system.out.println (" Sum of three numbers: "+sum (three-to-one)",         system.out.println ("Sum of four numbers:" +sum (1,2,3,4));     }    public static int sum (int a,int b) {         return a + b;    }     public static int sum (int a,int b,int c) {         return a + b + c;    }     public static int sum (int a,int b,int c,int d) {         return a + b + c + d;    }} 


Array

1. Array overview

It is now necessary to count the wages of a company's employees, such as calculating the average wage and finding the highest wage. Assuming that the company has 80 employees, with the knowledge previously learned, the program first needs to declare 80 variables to remember each employee's salary, and then proceed, it will be very troublesome. To solve this problem, Java provides an array for us to use.

An array is a container that stores multiple variables (elements). The data types of multiple elements are consistent. Arrays can store either the base data type or the reference data type.


2. Array definition Format

Format 1: Data type [] array name;

Format 2: Data type array name [];

These two are defined, and there are no element values in the array and need to initialize the arrays.


3. Initialization of arrays

Overview of array initialization: Arrays in Java must be initialized before they can be used. The so-called initialization is to allocate memory space for array elements in arrays and assign values to each array element.

How arrays are initialized:

Dynamic initialization: Only the array length is specified when initializing, and the initial value is assigned by the system array.

Static initialization: When eating petrified, specify the initial value of each array element, and the system determines the length of the array.


4. Dynamic initialization of arrays

Dynamic initialization: Only the array length is specified when initializing, and the initial value is assigned by the system.

Format: data type [] Array name = new data type [array length];

The length of the array is actually the number of elements in the array.

int[] arr = new int[3];== left: int: The data type of the element in the array is int type []: This is an array of arr: the name of the array = = right: New: The array allocates memory space int: The data type of the elements in the arrays is int type []: Description This is an array of 3: array length, which is actually the number of elements in the array



This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1855214

Methods and Arrays of 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.