Details about arrays and strings in Java

  • 2020-04-01 04:10:26
  • OfStack

Definition and use of Java arrays
If you want to save a set of data with the same type, you can use arrays.
Array definition and memory allocation

There are two types of syntax for defining arrays in Java:


  type arrayName[];
  type[] arrayName;


Type is any data type in Java, including primitive and composite types, and arrayName is the name of an array and must be a valid identifier, [] indicating that the variable is an array type variable. Such as:


int demoArray[];
int[] demoArray;


There is no difference between the two forms, the use effect is exactly the same, the reader can choose according to their own 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 in [], that is, the array length. Moreover, an array defined above cannot access any of its elements, so we have to allocate memory space for it. In this case, we need to use the operator new, whose format is as follows:
      ArrayName = new type [arraySize];
Where, arraySize is the length of the array and type is the type of the array. Such as:
DemoArray = new int [3].
Allocates the memory space occupied by three int integers to an integer array.

In general, you can allocate space at the same time. The syntax is:


  type arrayName[] = new type[arraySize];


Such as:


int demoArray[] = new int[3];


Initialization of an array

You can initialize the array at the same time as you declare it (static initialization) or after the declaration (dynamic initialization). Such as:


//Static initialization
//Static initialization At the same time, it allocates space and assigns values to the array elements 
int intArray[] = {1,2,3,4};
String stringArray[] = {" The school ", "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;

An array reference

An array can be referenced by subscripts:
 


  arrayName[index];


Unlike C and C++, Java overlooks array elements for security.

Each array has a length property to indicate its length, such as intarray.length to indicate the length of the array intArray.

Write a piece of code that requires the input of any five integers and the output of 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.length;
    
    //Assign values to array elements
    System.out.print(" Please enter the " + len + " , separated by Spaces: ");
    Scanner sc = new Scanner(System.in);
    for(int i=0; i<len; i++){
      intArray[i] = sc.nextInt();
    }
    
    //Calculates the sum of the array elements
    for(int i=0; i<len; i++){
      total += intArray[i];
    }
    
    System.out.println(" The sum of all array elements is: " + total);
  }
}

Operation results:
Please enter 5 integers separated by Spaces: 10, 20, 15, 25, 50
The sum of all array elements is: 120
Traversal of an array

In practice, you often need to iterate through groups to get each element in an array. The easiest way to think about this is the 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 results:


1, 2, 4, 7, 9, 192, 100,

However, Java provides an "enhanced" for loop for traversing groups with the syntax:


for( arrayType varName: arrayName ){
  // Some Code
}


ArrayType is the type of array (also the type of array element); VarName is a variable that holds the current element and changes its value every time it loops. ArrayName is the arrayName.

Each time you loop, you get the value of the next element in the array and save it to the varName variable until the end of the array. That is, the varName value of the first loop is the 0th element, and the second loop is the 1st element... Such as:


int arrayDemo[] = {1, 2, 4, 7, 9, 192, 100};
for(int x: arrayDemo){
  System.out.println(x + ", ");
}


The output is the same as above.

This enhanced for loop, also known as the "foreach loop," is a special simplified version of the regular for loop statement. All foreach loops can be rewritten as for loops.

However, if you want to use the index of the array, then the enhanced for loop cannot do that.
2 d array

The declaration, initialization, and references of two-dimensional arrays are similar to those of 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 the Java language, because two-dimensional arrays are treated as arrays of arrays, the array space is not allocated consecutively, so it is not required that two-dimensional arrays each have the same size. Such as:


int intArray[ ][ ] = { {1,2}, {2,3}, {3,4,5} };
int a[ ][ ] = new int[2][ ];
a[0] = new int[3];
a[1] = new int[5];

The product of two matrices is calculated from a two-dimensional array.


public class Demo {
  public static void main(String[] args){
    //The first matrix (initializes a two-dimensional array dynamically)
    int a[][] = new int[2][3];
    //The second matrix (statically initializes a two-dimensional array)
    int b[][] = { {1,5,2,8}, {5,9,10,-3}, {2,7,-5,-18} };
    //The 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);
    
    //Compute 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();
    }
  }
}

Operation results:


25  65  14  -65 
50  130 28  -130

Some notes:
This is a static array. Once a static array is declared, its capacity is fixed and cannot be changed. So when you declare an array, be sure to consider the maximum size of the array to prevent insufficient capacity.
If you want to change the capacity while the program is running, you need an ArrayList or a Vector.
Due to the shortcoming of fixed static array capacity, it is not used frequently in real development and is replaced by ArrayList or Vector, because it is often necessary to add or remove elements to the array in real development, and its capacity is not easy to estimate.

Java String (String)
On the surface, a string of data between the double quotes, such as "school", "http://www.weixueyuan.net", etc. In Java, you can define strings using the following methods:


  String stringName = "string content";


Such as:


String url = "http://www.weixueyuan.net";
String webName = " The school ";

Strings can be concatenated with "+", and the "+" operation between basic data types and strings will also be automatically converted to 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 + " , the result is  " + stuScore;
    System.out.println(info);
  }
}

Operation results:


 Xiao Ming's age is  17 , the result is  92.5

One thing String strings have in common with arrays is that they are initialized with the same length and the same content. If you change its value, a new string is generated, as shown below:


String str = "Hello ";
str += "World!";


This assignment looks a bit like a simple solitaire, with a "World!" after STR. String to form the final string "Hello World!" . Here's how it works: the program first produces a str1 string and requests a space in memory. It is not possible to append a new string at this point, because the length of the string is fixed after it is initialized. If you want to change it, you have to abandon the original space and reapply to be able to accommodate "Hello World!" String memory space, and then "Hello World!" String in memory.

In fact, String is a class under the java.lang package, and according to the standard object-oriented syntax, its format should be:


String stringName = new String("string content");


Such as:


String url = new String(http://www.weixueyuan.net);


But because String is so commonly used, Java provides a simplified syntax.

Another reason for using simplified syntax is that there is a lot of waste in memory usage with standard object-oriented syntax. For example, String STR = new String(" ABC "); Two String objects are actually created, one is the "ABC" object, stored in the constant space, and one is the space applied for the object STR using the new keyword.
String manipulation

The String object has many methods that make it easy to manipulate strings.
1) the length () method

Length () returns the length of the string, for example:


String str1 = " The school ";
String str2 = "weixueyuan";
System.out.println("The lenght of str1 is " + str1.length());
System.out.println("The lenght of str2 is " + str2.length());


Output results:


The lenght of str1 is 3
The lenght of str2 is 10

It can be seen that whether it is a letter, a number, or a Chinese character, the length of each character is 1.
2) the charAt () method

The charAt() method gets the specified character in the string by index value. Java dictates 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. Such as:


String str = "123456789";
System.out.println(str.charAt(0) + "  " + str.charAt(5) + "  " + str.charAt(8));


Output results:


1  6  9


3) the contains () method

The contains() method is used to detect if a string contains a substring, for example:


String str = "weixueyuan";
System.out.println(str.contains("yuan"));


Output results:


true


4) replace () method

String substitution 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", " The school ");
System.out.println(str1);
System.out.println(str2);


Output results:


The url of weixueyuan is www.weixueyuan.net!
The url of  The school  is www. The school .net!

Note: the replace() method does not change the original string, but instead generates a new string.
5) the split () method

Split the current string with the specified string as the separator. The result 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.split("_");
    System.out.println(Arrays.toString(strArr));
  }
}


Operation results:


[wei, xue, yuan, is, good]

The above are just a few common String object methods, more methods and detailed explanations refer to the API documentation.


Related articles: