Methods and Arrays of Java

Source: Internet
Author: User
Tags control characters sorts

Key points of knowledge:

    1. What is a method
    2. Format and properties of a method
    3. Characteristics of the method
    4. Introduction, declaration, and initialization of one-dimensional arrays
    5. Array Allocation memory space
    6. Two-dimensional arrays
    7. Tool class for manipulating arrays-arrays
    • What is a method

A method is a set of code blocks that are designed to implement a particular function. The main functions of the method are two:

    1. Structured Code : The code is organized according to the function, it is the code structure is clear, easy to read and modify, that is, the program maintainability is strong.
    2. Reduce code duplication : A fixed function that may be used more than once in a program, when used to call a written method, instead of repeating the corresponding function code.

The following two points should be noted when writing the method:

    1. Logical Rigor : A complete function of the method implementation, so when writing to take into account a variety of situations, and the corresponding treatment for each situation.
    2. Versatility (REUSABLE): The method is a function, in the implementation of the time, you can according to the needs of the method has a certain versatility, unless necessary, otherwise do not write a dedicated method.

Summary: A method is a collection of code snippets that can be reused, a section of the program that completes a separate function.

    • Format and properties of a method

define the format :

Modifier returns a value type function name (parameter type form parameter 1, parameter type parameter 2, ...) {
Execute the statement;
return value;
}

Properties in the method

Access control: Access control limits the visible scope of the method, or the scope of the method being called, the method has four access control characters, and public protected the default private. Let me introduce you in detail later.

Formal parameters: Used to receive data from outside input when the method is called.

Argument: The data that is actually passed to the method when the method is called.

Return value: Returns the data to the environment that called it after the method has finished executing.

Return value type: The data type of the pre-agreed return value, such as no return value, must be given the return type void.

The return statement can be omitted if the function returns a value of type void, and the system will help you add it automatically.

Function of return: End Function, End function.

Parameter list (type of parameter, number of parameters, order of parameters) as long as there is a different, then this parameter list is not the same, for the method, even if the same name is not the same method.

Method signature: The parameter list of the method name and method (can distinguish method).

Method called in the Java language: Object name. Method Name (argument list).

The number, data type, and order of the arguments must match the parameter list of the called method declaration.

Main function:

    1. This class is guaranteed to run independently.
    2. Because it is the entrance to the program.
    3. Because it is called by the JVM.

What is the method definition name for?

    1. In order to mark this function, it is convenient to call.
    2. In order to use the name can clarify functions of function, in order to increase the readability of the code.

overloading: in a class, if two or more than two of the same name methods appear, as long as their number of arguments, or different types of parameters, can be called the method overload.

How to differentiate overloads: When the method has the same name, only the argument list is seen, and the return value type has no relation.

Reason for existence: the difference in the same class of methods that masked an object is caused by different parameters.

Example:

 Public void A (int  a) {}publicint  A () {} Public void A (int a,string s) {}

    • characteristics of the method

Features: It can implement independent functions, must be defined in the class, it is only called to execute, it can be reused, the method ends after the object of the method loses the reference.

How do I define a function?

function is actually a function, the definition function is the realization function, through two explicit to complete.

    1. The result of the operation of this function is clearly defined as the return value type of the function.
    2. In the process of implementing this function, whether there is unknown content involved in the operation, in fact, is to clarify the function of the parameter list (parameter type & number of parameters)

Note: Functions can only be called, and functions cannot be defined.

Variable parameters:

Variable parameters have been developed from java1.5, which is an extension of Java methods and arrays.

The parameters that can be accepted in the method are no longer a fixed number, but are determined by how much specific requirements are passed.

define the format: return value type Method Name ( parameter type ... formal parameters) {    }

Characteristics of variable parameters: can only appear at the end of the parameter list.

... Between the variable type and the variable name, there are no spaces available.

When you call a method of a mutable parameter, the compiler creates an array for the mutable parameter implicitly, accessing the mutable parameter as an array in the method body.

    • Declaration and initialization of one-dimensional arrays

An Introduction to arrays:

An array is a basic data storage structure in the Java language that stores a container of the same type.

Benefit: The data in the container can be numbered, starting with 0, the array is used to encapsulate the data, and a specific entity is killed.

Java array: You must declare the array before allocating memory to the array. The array corresponds to a contiguous space in memory.

The data element must be of the same data type, or it can be a reference data type, but the elements in the same array must be of the same class data type.

one-dimensional arrays : it can be understood as a column of multiple rows, with the same type of data, where each data is called an array element. Once the length of the array is determined, it cannot be changed, that is, the array is fixed length.

The Java language cannot specify its length (the number of elements) when declaring an array.

int a[5]        // illegal    

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

There are two ways to initialize an array:

  Static initialization : The initial value of each array element is specified by us at initialization, with the system determining the desired array length,

Format: Array name = new array type []{element 1, Element 2, Element 3 ... Element n};

Simplified Syntax: array name = {element 1, element 2, Element 3 ... Element n};

  Dynamic Initialization: The length of the array is specified by us when initializing, and the initial value is assigned by the system array element.

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

  Note : You cannot use both static and dynamic initialization, that is, you cannot specify both the length and the element of the array.

    • Array Allocation memory space

Partitioning of Java memory

    1. Register: The area covered by the CPU.
    2. Where the function is stored.
    3. Local method Area: is a system-related code storage area.
    4. Stack memory: Stored is a local variable, the variable operation area at the end of the release, (Local variables: Methods on the parameters, variables within the method, variables in the statement)
    5. Heap Memory: The storage of arrays and objects, simply said, heap memory is stored in entities, the entity is the place where multiple data can be stored, remember: As long as it is built with new is stored in the heap memory.

Feature: Any entity has a memory address value. The variables in the heap memory have a default initial value, garbage collection mechanism.

Memory allocations for arrays:

Defining an array of int scores will allocate memory space for scores in stack memory, whose value is an indeterminate value. When the statement scores = Int[5] is executed, it allocates 5 spaces in the heap memory, 4 bytes per space, for the integer data, with an initial value of 0, and then assigns the first address of the space, that is, the primary element address, such as 0x3000, to the scores variable. The address is equivalent to a pointer to the allocated space in the heap memory, where 5 of the allocated space in the heap memory can be represented by scores[0]-scores[4], and when the four assignment statements are executed, the corresponding element position is populated with the specified value, and if NULL is assigned to scores at this time, Scores will no longer point to any location where the allocated space in the heap memory becomes garbage and is reclaimed by the garbage collector at some point.

Defining variables in a method, including basic data type variables and reference data type variables, allocates space in the stack memory and is automatically reclaimed when the scope of the variable is exceeded.

Summary: Initialize = define array + Allocate space + assignment.

    • Two-dimensional arrays

two-dimensional arrays : actually a one-dimensional array, and each of its elements is a one-dimensional array.

Static initialization

int []  newint[][]{{1,2},{3,4},{5,6}}; int []  arr = {{1,2},{3,4},{5,6}};

Dynamic initialization

int [[]  newint[3][2];

    • Tool class for manipulating arrays-arrays

Static boolean[] CopyOf (type[] original, int newlength) Copy the specified array see the following remarks

Static byte[] Copyofrange (type[] original, int from, int to) copies the specified range of the array to a new array.

Static Boolean Equals (Type[] A, type[] A2) returns true if two array lengths are equal and element one by one is equal

static void Fill (type[] A, type Val) assigns all elements of a array to Val.

The static void Fill (type[] A, int fromIndex, int toindex, type val) assigns the elements of a array from Formindex to Tiondex indexes to Val.

static void sort (type[] a)//sort (int[] arr) sorts the specified array in ascending order of numbers.

The static void sort (type[] A, int fromIndex, int toindex) sorts the elements between the specified array from the Formindex to the Tiondex index in ascending order of numbers.

The static string toString (type[] a) returns a string representation of the contents of the specified array. Multiple array elements are separated by commas or spaces.

The static int BinarySearch (type[] A, type key) uses the binary search method to search the index of the key element in the array, and returns a negative number if the a array does not include the key. (The method must have been sorted in ascending order and then called).

The static int BinarySearch (type[] A, int fromIndex, int toindex, type key) uses the binary search method to search the index of the key element in the array from FromIndex to Toindex;

If the A array does not include key, a negative number is returned. (The method must have been sorted in ascending order and then called).

Summary: Using the Array tool class can save time, improve efficiency, and pay attention to long lookup APIs.

Methods and Arrays of Java

Related Article

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.