Detailed knowledge of array and string related in Java _java

Source: Internet
Author: User
Tags array definition constant memory usage

Definition and use of Java arrays
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 types of syntax for defining arrays in Java:

  Type arrayname[];
  Type[] Arrayname;


Type is any data type in Java, including the base type and combination type, arrayname the array name, and must be a valid identifier, [] to indicate that the variable is an array type variable. For example:

int demoarray[];
Int[] Demoarray;


There is no difference between the two forms, the effect is exactly the same, the reader can choose according to their own programming habits.

In contrast to C, 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. And for an array like the one that doesn't have access to any of its elements, we have to allocate the memory space for it to use the operator new, which is formatted as follows:
Arrayname=new Type[arraysize];
Where ArraySize is the length of the array, type of the array. Such as:
Demoarray=new Int[3];
Allocates the memory space occupied by 3 int integers for an integer array.

In general, you can allocate space at the same time as the definition, and the syntax is:

  Type arrayname[] = new Type[arraysize];


For example:

int demoarray[] = new INT[3];


Initialization of arrays

You can initialize (statically initialize) the array at the same time as you declare it, or you can initialize it after the declaration (dynamic initialization). For example:

Static initialization
//static initialization allocates space for array elements and assigns
int intarray[] = {1,2,3,4};
String stringarray[] = {"Micro-study Court", "Http://www.weixueyuan.net", "all programming languages are paper Tigers"};
Dynamic initialization of
float floatarray[] = new Float[3];
Floatarray[0] = 1.0f;
FLOATARRAY[1] = 132.63f;
FLOATARRAY[2] = 100F;

Array reference

You can refer to an array by subscript:

  Arrayname[index];


In contrast to C, C + +, Java array elements are checked across borders to ensure security.

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

"Example" writes a piece of code that requires any 5 integers to be entered, outputting their and.

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 a value to an array element
    System.out.print ("Please enter" + len + "integer, separated by a space:");
    Scanner sc = new Scanner (system.in);
    for (int i=0; i<len; i++) {
      Intarray[i] = Sc.nextint ();
    }
    
    Computes the and for of the array element
    (int i=0; i<len; i++) {Total
      = intarray[i];
    
    System.out.println ("and for all array elements:" + total);
  }

Run Result:
Please enter 5 integers separated by spaces: 10 20 15 25 50
The and of all array elements are: 120
Traversal of arrays

In actual development, it is often necessary to traverse the array to get every element in the array. The easiest way to think about it is for loops, for example:

int arraydemo[] = {1, 2, 4, 7, 9, N-();
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 a "enhanced" for loop that is designed to traverse an array, and the syntax is:

for (ArrayType varname:arrayname) {
  //Some Code
}


ArrayType the array type (also the type of the element); VarName is the variable that holds the current element, and the value of each loop changes; arrayname the array name.

Once per loop, the value of the next element in the array is fetched and saved to the VarName variable until the array ends. That is, the first loop varName the value of the No. 0 element, the second loop is the 1th element ... For example:

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


The output results are the same as above.

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

However, if you want to use the index of an array, the enhanced version of the For loop is not possible.
Two-dimensional array

The 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] =;
A[0][1] =;
// ......
A[1][2] = 93;

In the Java language, the array space is not continuously allocated because it is considered an array of arrays, so it is not required to have the same size for each dimension of the two-dimensional array. 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" computes the product of two matrices through a two-dimensional array.

public class Demo {public
  static void Main (string[] args) {
    //First matrix (dynamic initialization of a two-dimensional array)
    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}};
    Result Matrix
    int c[][] = new Int[2][4];
    
    Initializes 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 ();}}

Run Result:

  -65  130  -130

A few notes:
The above is a static array. Once a static array is declared, its capacity is fixed and cannot be changed. So when declaring an array, be sure to consider the maximum size of the array to prevent the phenomenon of insufficient capacity.
If you want to change the capacity when you run the program, you need to use an array list (ArrayList, also called a dynamic array) or vector (vectors).
Because of the disadvantage of static array capacity fixing, the usage frequency is not high in actual development, and is replaced by ArrayList or Vector, because it is often necessary to add or remove elements to an array in actual development, and its capacity is not predictable.

Java String (String)
On the surface, the string is the data between the double quotes, such as "micro-garden", "http://www.weixueyuan.net" and so on. 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 = "Micro-learning Court";

Strings can be connected by "+", and the "+" operation of the base data type and string is typically automatically converted to a string, for example:

public class Demo {public
  static void Main (string[] args) {
    String stuname = "Xiaoming";
    int stuage =;
    float stuscore = 92.5f;
    
    String info = stuname + "The Age is" + Stuage + ", the result is" + Stuscore;
    SYSTEM.OUT.PRINTLN (info);
  }

Run Result:

Xiaoming's age is 17, and his grade is 92.5.

String strings have one thing in common with arrays, that is, they are initialized, the length is constant, and the contents are unchanged. If you want to change its value, a new string is generated, as follows:

String str = "Hello";
STR + + "world!";


This assignment expression looks a bit like simple solitaire, followed by a "world!" directly behind Str String that forms the final string "Hello world!". It works like this: The program first produces the STR1 string and applies a space in memory. It is not possible to append a new string at this time, because the length is fixed after the string is initialized. If you want to change it, only give up the original space, reapply to be able to accommodate "Hello world!" The memory space of the string and then "Hello world!" The string is placed in memory.

In fact, a String is a class under the Java.lang package, and in the standard object-oriented syntax, the format should be:

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


For example:

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


However, because string is particularly common, Java provides a simplified syntax.

Another reason to use simplified syntax is that, in the standard object-oriented syntax, there is a lot of waste in memory usage. For example, string str = new String ("abc"), actually creates two string objects, one is an "ABC" object, is stored in a constant space, and one is the space that uses the new keyword to apply to str.
String manipulation

String objects have many methods that allow you to manipulate strings easily.
1) Length () method

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

String str1 = "Micro-learning court";
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 the length of each character is 1, whether it is a letter, a number, or a Chinese character.
2) CharAt () method

The function of the CharAt () method is to obtain the specified character in the string according to the index value. Java stipulates that the index value of the first character in the 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 results:

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 results:

True


4) Replace () method

String substitution, which replaces all specified substrings in the string, for example:

String str1 = "The URL of Weixueyuan is www.weixueyuan.net!";
String str2 = Str1.replace ("Weixueyuan", "micro-court");
System.out.println (STR1);
System.out.println (STR2);


Output results:

The URL of Weixueyuan is www.weixueyuan.net!
The URL of the micro-learning Court is www. Micro Court. net!

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

Splits the current string with the specified string as the delimiter, and the result of the split 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));
  }


Run Result:

[Wei, Xue, Yuan, is, good]

These are just a few of the common methods for string objects, and for more methods and detailed explanations, refer to the API documentation.

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.