Examples of using array and string types in Java

  • 2020-04-01 04:08:49
  • OfStack

Java array

An array is a collection of a set of data with the same data type, Java support for arrays, each basic unit is the basic of one-dimensional array data types of data, a two-dimensional array is each basic unit is a one-dimensional array of one dimensional array, and so on, n-dimensional array of each basic unit is n - 1 for an array of n - 1 d array. Let's take a one-dimensional array as an example to illustrate the use of Java arrays.

1. Array declaration

Array declarations can take the following two forms (with different positions of square brackets) :


int arr[];
int[] arr2;

2. Array initialization

Array initialization can also take two forms, as follows (with or without new) :


int arr[] = new int[]{1, 3, 5, 7, 9};
int[] arr2 = {2, 4, 6, 8, 10};

3. Go through the groups

Traversal groups can be used for/foreach, as follows:

   


 public static void main(String[] args) {
    int arr[] = new int[]{1, 3, 5, 7 ,9};
    int[] arr2 = {2, 4, 6, 8, 10};
    for (int i = 0; i < arr.length; ++i) {
      System.out.print(arr[i] + "t"); // 1 3 5 7 9
    }
    for (int x: arr2) {
      System.out.print(x + "t"); // 2 4 6 8 10
    }
  }

4. Arrays.fill() fills the array

Using the static methods of the Arrays class requires the import package java.util.Arrays, which defines many overloaded methods.

Void fill(int[] a, int val
Void fill(int[] a, int fromIndex, int toIndex, int val) fills the element of the specified index

             


 int[] arr3 = new int[5];
    for (int x: arr3) {
      System.out.print(x + "t"); //Zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero zero
    }
    System.out.println();
    Arrays.fill(arr3, 10);
    for (int x: arr3) {
      System.out.print(x + "t"); //10, 10, 10, 10, 10, all filled with 10
    }
    System.out.println();
    Arrays.fill(arr3, 1, 3, 8);
    for (int x: arr3) {
      System.out.print(x + "t"); //10, 8, 8, 10, 10 populates the specified index
    }
    System.out.println();


5. Arrays.sort() sorts Arrays

Void sort(int[] a) all sorts
Void sort(int[] a, int fromIndex, int toIndex) sorts the elements of the specified index

             


 int[] arr4 = {3, 7, 2, 1, 9};
    Arrays.sort(arr4);
    for (int x: arr4) {
      System.out.print(x + "t"); // 1 2 3 7 9
    }
    System.out.println();
    int[] arr5 = {3, 7, 2, 1, 9};
    Arrays.sort(arr5, 1, 3);
    for (int x: arr5) {
      System.out.print(x + "t"); // 3 2 7 1 9
    }
    System.out.println();

6. Arrays.copyof (

Int [] copyOf(int[] original, int newLength
Int [] copyOfRange(int[] original, int from, int to) copies an array, specifying the index of the original array being copied

         


  int[] arr6 = {1, 2, 3, 4, 5};
    int[] arr7 = Arrays.copyOf(arr6, 5); // 1 2 3 4 5
    int[] arr8 = Arrays.copyOfRange(arr6, 1, 3); // 2 3
    for (int x: arr7) {
      System.out.print(x + "t");
    }
    System.out.println();
    for (int x: arr8) {
      System.out.print(x + "t");
    }
    System.out.println();

Java string
The Java String type is the String class. Here's how to manipulate strings.

1. String concatenation

String concatenation USES the "+" symbol, as in the following example:


    String s = new String("Hello");
    String s2 = new String("World");
    System.out.println(s + " " + s2); // Hello World

2. Get the string length

Get the string length using STR. Length (), as in the following example:


    String s3 = new String("Hello Java");
    System.out.println(s3.length()); // 10

Gets the index of the specified string

Gets the indexOf the specified string using STR. IndexOf(substr), STR. LastIndexOf (substr), as in the following example:


    String s4 = new String("how are you");
    System.out.println(s4.indexOf("o")); //1. Start from scratch
    System.out.println(s4.lastIndexOf("o")); //9 start at the tail

Gets the character of the specified index

Gets the character of the specified index using STR. CharAt (index), as in the following example:


    String s5 = new String("Hello Java");
    System.out.println(s5.charAt(4)); // o

5. Remove Spaces from the string

There are different ways to remove the Spaces in the string, use STR. The trim () or STR. The replaceAll (regex, replacement), may also use the StringTokenizer class to separated string using the blank space, need to import package before use Java. Util. StringTokenizer, examples are as follows:

           


 String s6 = new String(" Hello Java ");
    String s7 = s6.trim(); //Removes Spaces at the beginning and end of a string
    String s8 = s6.replaceAll(" ", ""); //Replaces all Spaces in the string
    StringTokenizer st = new StringTokenizer(s6, " "); //Use Spaces to separate strings
    StringBuffer sb = new StringBuffer();
    while (st.hasMoreTokens()) {
      sb.append(st.nextToken());
    }
    System.out.println(""" + s6 + """ + "length = " + s6.length()); // " Hello Java "length = 14
    System.out.println(""" + s7 + """ + "length = " + s7.length()); // "Hello Java"length = 10
    System.out.println(""" + s8 + """ + "length = " + s8.length()); // "HelloJava"length = 9
    System.out.println(""" + sb.toString() + """ + "length = " + sb.toString().length()); // "HelloJava"length = 9

Replace the string

The replacement string can replace all substrings or the first substring, as shown in the following example:

             


 String sr = new String("abc abd bcd");
    String sr2 = sr.replace("ab", "xx"); //Replace all substrings
    String sr3 = sr.replaceFirst("ab", "xx"); //Replace the first string
    System.out.println(sr2); // "xxc xxd bcd"
    System.out.println(sr3); // "xxc adb bcd"

7. String judgment, etc

There are a variety of situations, such as string content, whether to ignore case, memory address, etc., string at the beginning or end of the judgment, such as the following example:

         


  String se = new String("Summer is so Hot");
    String se1 = new String("Summer is so Hot");
    String se2 = new String("summer is so hot");
    String se3 = se;
    System.out.println(se == se1); //False compares memory instead of string content
    System.out.println(se == se3); // true
    System.out.println(se.equals(se1)); //True compares string contents
    System.out.println(se.equals(se2)); // false
    System.out.println(se.equalsIgnoreCase(se2)); //True ignores case
    System.out.println(se2.startsWith("summer")); //True string start
    System.out.println(se2.endsWith("cold")); //False string ending

8, string case conversion

The following example of string case conversion:

         


  String sc = new String("hello WORLD");
    String scl = sc.toLowerCase(); //Hello world to lowercase
    String scu = sc.toUpperCase(); //HELLO WORLD to uppercase
    System.out.println(scl + " " + scu);

9. String separation

The following example of string separation:

         


  String ss = new String("abc,def,g,h");
    String[] ss2 = ss.split(","); //Separated by commas
    for (String x: ss2) {
      System.out.print(x + "t"); // abc def g h
    }

10. Format a string

There are many forms of string formatting, such as Date formatting, time formatting, and hexadecimal conversion, etc. The use of Date class requires the import package java.util.Date, as shown in the following example:


    Date d = new Date();
    System.out.println(d); //Wed Jul 22 16:00:36 CST 2015 default format
    System.out.println(String.format("%tm", d)); //07 double digit months
    System.out.println(String.format("%tH", d)); //16 two for 24 hours
    System.out.println(String.format("%x", 256)); //One hundred hexadecimal

Class comparison of String, StringBuffer, and StringBuilder

String: String constant, immutable object. When the variable contents are changed, a new String object is actually generated. When the variable contents are changed many times and frequently, the system performance will be affected.

StringBuffer: a String variable, thread-safe, that operates on the same object when its contents change, more efficiently than a String.

StringBuilder: string variable, compatible with StringBuffer, but not thread-safe. If it's a single thread, use StringBuilder first, which is faster than StringBuffer.


Related articles: