Dark Horse Programmer--java Basic Syntax (c)---array

Source: Internet
Author: User
Tags array definition array length

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

The main content of this blog post is the third part of the Java syntax--arrays, arrays, and collections of the same type of data. In fact, an array is a container. The array automatically numbers the elements in the array starting with 0, which makes it easy to manipulate the elements.

First, the definition of the array

Array format one: element type [] Array name = new element type [element number or array length]; e.g. int[] arr=new int[5];

Array definition Format two: element type [] Array name =new element type []{element, element, ...}; such as: int[] arr=new int[]{1,2,3,4,5}; This method can also be shortened to int[] arr ={1,2,3,4,5};

When a Java program runs, it needs to allocate space in memory. The process by which an array allocates space in memory as shown in the program runtime:

Int[] Arr=new int[4];

   

When the program runs, it stores four integers in the heap memory and assigns the memory address to the variable arr in the stack memory.

In order to improve the computational efficiency, Java divides the space into different regions, and has specific processing data mode and memory management mode for each area.

Memory Partition: 1, register, 2, method area, 3, local method area, 4, stack memory, 5, heap memory.

The stack memory and heap memory used in the array are highlighted here, and the rest of the memory is explained in detail later.

1, Stack memory: used to store local variables, when the scope of the variable to the end, the occupied space will be automatically released.

2. Heap Memory: Arrays and objects, and the instances created by new are stored in heap memory. Each entity has a memory address value. Variables in an entity have default initialization values, which vary depending on the type. The integer type is 0, the decimal type is 0.0, or the 0.0f,boolean type is the False,char type is ' \u0000 '. If you set the reference entity of an array to null, that is, the entity is no longer being used, it is reclaimed by the garbage collector for an indeterminate period of time.

Ii. Common exceptions to arrays

  Common exceptions to arrays fall into two categories:

1. Array pin out-of-bounds exception (arrayindexoutofboundsexception): Occurs when a non-existent script in the array is accessed.

2. Null pointer exception (NULLPOINTEREXCEPTION): This exception occurs when the reference variable does not point to any entity, using it to manipulate the entity.

Examples of specific exceptions are shown in the following code:

1 classTestdemo2 {3      Public Static voidMain (string[] args)4     {5         int[] arr=New int[5];6System.out.println (Arr[5]);//accessing a non-existent foot tag in an array7 8Arr=NULL;9System.out.println (Arr[0]);//Reference Variabledoes not point to any entities when accessing specific elements. 
Ten     }one}

When printing an array, if the reference variable of the array is printed directly, the result of the printout is the hash value of the initial address of the array. For example: "[[email protected]", [I represents an array of type int, 123FFF represents the hash value of the initial address of the array.

Iii. operation of arrays

The basic operation of an array is to save and fetch. The storage and fetching of an array is achieved by means of a foot tag.

The next step is to traverse and print all the elements of the array.

  

1 Static void PrintArray () 2     {3         int[] arr={12,33,44,55,66,77}; 4          for (int i=0;i<arr.length;i++) 5         {6             System.out.println ("arr[" +i+ "] =" +arr[i]); 7         }8     }

The results are printed as follows:

  

The sorting of arrays is described in detail in another blog post, which is not covered here, this post mainly introduces a basic concept and operation of data.

Four or two-point lookup method  

Here we introduce the classical method of array lookup--binary search method. A binary lookup, also called a binary lookup, is an algorithm for locating data quickly, and is typically used to determine where to insert data in given an ordered array. If an element is stored in the array, and the array is guaranteed to be orderly, the value returned by the binary lookup method is the pin that the element is inserted into.

In the actual development, the binary search does not need us to write, the JDK has provided the relevant API for invocation. Is Arrays.binarysearch (int[] arr,int num). Here we are through our own code to achieve a two-point search is mainly familiar with the idea of this algorithm, learning the algorithm to solve the problem of the pattern.

So the specific code is as follows:

1 Static intBinarySearch (int[] arr,intnum)2     {3         intMin=0,max=arr.length,mid=0;4          while(min<=max)5         {6Mid= (Min+max)/2;//Locate the middle position of the array7             if(Arr[mid]>num)//if the target value is smaller than the median value, then the data is on the small side, and the foot of the maximum value becomes one of the smaller middle values. 8Max=mid-1;9             Else if(Arr[mid]<num)//if the target value is larger than the median value, the data is on this side of the large, and the smallest foot is changed to the middle value plus one. TenMin=mid+1; One             Else A                 returnMid//if equal, the description is found.  -         } -         returnMin//if the loop is finished and the program has not returned a description that is not found, the smallest foot mark at this point is the toe of the insertion point.  the}

The code in the main function is:

1  Public Static void  2    {3         int[] arr =newint[]{ 12,13,14,55,57,76};; 4         System.out.println (BinarySearch (arr,15)); 5     }

The output is:

 

The caret that returns the insertion point is 3, and indeed the 15 insert array ensures that the array remains in an orderly position.

Five or two-d arrays

A two-dimensional array can be understood as an array of arrays.

As with normal arrays, two-dimensional arrays also have three definition formats:

Format one:

int[][] arr = new int[3][2];

There are three one-dimensional arrays in a two-dimensional array, with two elements in each array.

Format two:

int[][] arr = new int[3][];

There are 3 one-dimensional arrays in the two-dimensional array, each one-dimensional array is the default initialization value NULL, and the three one-dimensional arrays can be initialized individually.

Format three:

Int[][] arr={{1,2,3},{4,5},{6,7,8,9}};

Defines a two-dimensional array called arr, with three one-dimensional arrays in a two-dimensional array, and the specific elements in each one-dimensional array are initialized.

To familiarize ourselves with the two-dimensional array, we also iterate through all the elements like a one-dimensional array.

The specific code is as follows:

1 Static voidPrintarr ()2     {3         int[] arr={{1,2,3,4},{5,6,7},{8,9},{10}};4          for(inti=0;i<arr.length;i++)5         {6              for(intj=0;j<arr[i].length;j++)//Double loop traversal of two-dimensional arrays7             {8System.out.print ("arr[" +i+ "[" +j+ "] =" +arr[i][j]+ "\ T");9             }TenSystem.out.println ();//returns a newline after each dimension array output is complete.  One         } A}

The output is:

  

All the summaries of this array have been sorted out.

Keep on trying to refuel! For tomorrow's better self.

  

Dark Horse Programmer--java Basic Syntax (c)---array

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.