Definition and use of Java arrays <br />If you want to save a set of data of the same type, you can use an array.
Array definition and memory allocation
There are two syntaxes for defining arrays in Java:
type arrayName[]; type[] arrayName;
type is any data type in Java, including basic types and combination types. arrayName is the array name and must be a legal identifier. [ ] indicates that the variable is an array type variable. For example:
int demoArray[];int[] demoArray;
There is no difference between these two forms, and the use effect is exactly the same. Readers can choose according to their programming habits.
Unlike C and C++, Java does not allocate memory for array elements when defining arrays, so there is no need to specify the number of array elements, that is, the length of the array. Moreover, for an array defined above, it cannot access any of its elements. We must allocate memory space for it. At this time, the operator new is used, and its format is as follows:
arrayName=new type[arraySize];
where arraySize is the length of the array and type is the type of the array. like:
demoArray=new int[3];
Allocate the memory space occupied by 3 int integers to an integer array.
Usually, you can allocate space while defining, with the syntax as:
type arrayName[] = new type[arraySize];
For example:
int demoArray[] = new int[3];
Initialization of arrays
You can initialize (static initialization) while declaring the array, or you can initialize it after declaration (dynamic initialization). For example:
// Static initialization // While static initialization, it allocates space to array elements and assigns the value int intArray[] = {1,2,3,4};String stringArray[] = {"WeChatyuan", "http://www .weixueyuan.net", "All programming languages are paper tigers"};// Dynamic initialization float floatArray[] = new float[3];floatArray[0] = 1.0f;floatArray[1] = 132.63f;floatArray[2 ] = 100F;Array reference
An array can be referenced by subscript:
arrayName[index];
Unlike C and C++, Java must conduct out-of-bounds checks on array elements to ensure security.
Each array has a length attribute to indicate its length, for example, intArray.length specifies the length of the array intArray.
[Example] Write a piece of code that requires input of any 5 integers and output their sum.
import java.util.*;public class Demo { public static void main(String[] args){ int intArray[] = new int[5]; long total = 0; int len = intArray.len gth; // Give array elements Assign System.out.print("Please enter" + len + "Integers, separated by spaces:"); Scanner sc = new Scanner(System.in); for(int i=0; i<len; i++) { intArray[i] = sc.nextInt(); } // Calculate the sum of array elements for(int i=0; i<len; i++){ total += intArray[i]; } System.out.println(" The sum of all array elements is: " + total); }} Running results:
Please enter 5 integers, separated by spaces: 10 20 15 25 50
The sum of all array elements is: 120
Array traversal
In actual development, it is often necessary to traverse the array to get every element in the array. The easiest way to think of is a for loop, for example:
int arrayDemo[] = {1, 2, 4, 7, 9, 192, 100};for(int i=0,len=arrayDemo.length; i<len; i++){ System.out.println(arrayDemo[i ] + ", ");}
Output result:
1, 2, 4, 7, 9, 192, 100,
However, Java provides an "enhanced version" for loop, which is specifically used to traverse arrays, with the syntax as:
for( arrayType varName: arrayName ){ // Some Code}
arrayType is an array type (also the type of array element); varName is a variable used to save the current element, and its value will change every time the loop is looped; arrayName is the array name.
Each loop is done, the value of the next element in the array is obtained and saved to the varName variable until the end of the array. That is, the value of varName in the first loop is the 0th element, and the second loop is the 1st element... For example:
int arrayDemo[] = {1, 2, 4, 7, 9, 192, 100};for(int x: arrayDemo){ System.out.println(x + ", ");}
The output result is the same as above.
This enhanced version of for loop is also called a "foreach loop", which is a special simplified version of ordinary for loop statements. All foreach loops can be rewritten into for loops.
However, if you want to use the index of an array, the enhanced for loop cannot do it.
Two-dimensional array
Declaration, initialization, and reference of two-dimensional arrays are similar to one-dimensional arrays:
int intArray[ ][ ] = { {1,2}, {2,3}, {4,5} };int a[ ][ ] = new int[2][3];a[0][0] = 12;a[0][1] = 34;// ......a[1][2] = 93; In Java language, since two-dimensional arrays are regarded as arrays of arrays, the array space is not continuously allocated, so the size of each dimension of the two-dimensional array is not required to be the same. For example:
int intArray[ ][ ] = { {1,2}, {2,3}, {3,4,5} };int a[ ][ ] = new int[2][ ];a[0] = new int[3];a[1] = new int[5]; [Example] Calculate the product of two matrices through a two-dimensional array.
public class Demo { public static void main(String[] args){ // The first matrix (dynamic initialization of a two-dimensional array) int a[][] = new int[2][3]; // The second Matrix (statically initializes a 2D array) int b[][] = { {1,5,2,8}, {5,9,10,-3}, {2,7,-5,-18} } ; // Result matrix int c[][] = new int[2][4]; // Initialize the first matrix for(int i=0; i<2; i++) for(int j=0; j< 3 ;j++) a[i][j] = (i+1) * (j+2); // Calculate the matrix product for (int i=0; i<2; i++){ for (int j=0; j<4; j++){ c[i][j]=0; for(int k=0; k<3; k++) c[i][j] += a[i][k] * b[k ][j]; } } // Output settlement result for(int i=0; i<2; i++){ for (int j=0; j<4; j++) System.out.printf("%-5d" , c[i][j]); System.out.println(); } }} Running results:
25 65 14 -65 50 130 28 -130
A few explanations:
The above is a static array. Once a static array is declared, its capacity is fixed and cannot be changed. Therefore, when declaring an array, you must consider the maximum capacity of the array to prevent insufficient capacity.
If you want to change the capacity when running a program, you need to use an array list (ArrayList, also known as a dynamic array) or a vector (Vector).
It is precisely because of the disadvantage of fixed capacity of static arrays that are not used frequently in actual development and are replaced by ArrayList or Vector, because in actual development, it often needs to add or delete elements to the array, and its capacity is not easy to estimate.
Java String (String)
On the surface, strings are data between double quotes, such as "Weixueyuan", "http://www.weixueyuan.net", etc. In Java, you can use the following method to define a string:
String stringName = "string content";
For example:
String url = "http://www.weixueyuan.net";String webName = "WeChatyuan";
Strings can be concatenated through "+". Basic data types and strings perform "+" operations, which are generally automatically converted into strings, for example:
public class Demo { public static void main(String[] args){ String stuName = "Xiao Ming"; int stuAge = 17; float stuScore = 92.5f; String info = stuName + "The age is " + stuAge + ", and the grade is " + stuScore; System.out.println(info); }} Running results:
Xiao Ming's age is 17 and his grade is 92.5
String strings have one thing in common with arrays, that is, after they are initialized, their length remains unchanged and their content remains unchanged. If you want to change its value, a new string will be generated, as shown below:
String str = "Hello ";str += "World!";
This assignment expression looks a bit like a simple solitaire, adding a "World!" string directly after str to form the final string "Hello World!". The operating principle is as follows: the program first generates a str1 string and applies for a piece of space in memory. It is impossible to append a new string at this time because the length of the string is fixed after it is initialized. If you want to change it, you can only give up the original space, reapply for the memory space that can accommodate the "Hello World!" string, and then put the "Hello World!" string into memory.
In fact, String is a class under the java.lang package. According to the standard object-oriented syntax, its format should be:
String stringName = new String("string content");
For example:
String url = new String(http://www.weixueyuan.net);
However, since String is particularly commonly used, Java provides a simplified syntax.
Another reason for using simplified syntax is that according to the standard object-oriented syntax, there is a relatively large waste in memory usage. For example, String str = new String("abc"); actually creates two String objects, one is the "abc" object, stored in a constant space, and the other is the space applied for the object str using the new keyword.
String operation
There are many ways to operate strings easily.
1) length() method
length() returns the length of the string, for example:
String str1 = "Weixueyuan";String str2 = "weixueyuan";System.out.println("The length of str1 is " + str1.length());System.out.println("The length of st r2 is " + str2.length());
Output result:
The length of str1 is 3The length of str2 is 10
It can be seen that the length of each character is 1, whether it is letters, numbers, or Chinese characters.
2) charAt() method
The function of the charAt() method is to obtain the specified characters in the string according to the index value. Java stipulates that the index value of the first character in a string is 0, the index value of the second character is 1, and so on. For example:
String str = "123456789";System.out.println(str.charAt(0) + " " + str.charAt(5) + " " + str.charAt(8));
Output result:
1 6 9
3) contains() method
The contains() method is used to detect whether a string contains a substring, for example:
String str = "weixueyuan";System.out.println(str.contains("yuan"));
Output result:
true
4) replace() method
String replacement, used to replace all specified substrings in a string, for example:
String str1 = "The url of weixueyuan is www.weixueyuan.net!";String str2 = str1.replace("weixueyuan", "Weixueyuan");System.out.println(str1);Syste m.out.println(str2 );
Output result:
The url of weixueyuan is www.weixueyuan.net!The url of Weixueyuan is www.weixueyuan.net!
Note: The replace() method does not change the original string, but generates a new string.
5) split() method
Use the specified string as the delimiter to split the current string. The result of the segmentation is an array, for example:
import java.util.*;public class Demo { public static void main(String[] args){ String str = "wei_xue_yuan_is_good"; String strArr[] = str.spli t("_"); System.out.println(Arrays .toString(strArr)); }}
Running results:
[wei, xue, yuan, is, good]
The above only lists a few commonly used methods of String objects. For more methods and detailed explanations, please refer to the API documentation.