Java basics _day08_(API,String class, StringBuilder class)

Keywords: Java Programming JDK

Content summary:

  • API overview
  • String class (string class)
  • StringBuilder class (string buffer class)

1. API overview

1.1 Overview:

API(Application Programming Interface) is an application programming interface. API in Java refers to Java classes of various functions provided in JDK.

1.2 Usage:

Search Java classes that need to be queried using the index function in API documents.
b) Searching for related classes, we need to pay attention to a few points:
The package in which the class is located, if it is under the java.lang package, does not need to be used as a guide package.
The descriptive information of a class is to clarify its functions.
Constructing methods: What are the ways to create objects of this class?
Membership methods: Focus on return value types, method names, formal parameters.

2. String class

2.1 Overview of String classes:

String classes represent strings, and all string literals (such as "abc") in Java programs are implemented as examples of this class.
Strings are constants; their values cannot be changed after creation.
The essence of a string is an array of characters.
String is a special type of reference data. The direct output of string object is the data in the object.

2.2 String class construction method:

String(String original): Encapsulating string data into string objects;
String(char[] str): encapsulate the data of the character array into string objects;
String(char[] value,int index,int count): encapsulates part of the data in the character array as a string object. Index is the initial index value and count is the number of characters.

2.3 Distinction between String Objects Created by Constructing Method and Direct Assignment Method:

The string object created by the constructor is in heap memory, and the string object created by direct assignment is in the constant pool of the method area.

Case study:

public class StringDemo {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = "hello";

        // s1 and s2 point to the same string object in the constant pool in the method area, so the output address value is the same
        System.out.println((s1==s2));   // true

        s1 = "helloWorld";
        // Reassigning the value of s1 is equivalent to recreating a string object in a constant pool, and the result is false
        System.out.println((s1==s2));   // false
        // Because the string object pointed to by s1 changes, but s2 still points to the previous string, the output of s2 remains unchanged.
        System.out.println(s2);         // hello


        String s3 = new String("hello");
        String s4 = s3; 
        // If s4 is also pointed to the string object in heap memory, then the address values of s3 and s4 are equal.
        System.out.println(s3==s4);     // true

        // Pointing s3 to a new string is equivalent to pointing s3 to a string object in the constant pool
        s3 = "helloworld";
        // s3 points to the string object in the constant pool, s4 points to the string entity in heap memory, and then points to the string in the constant pool through the entity.
        // The address values of s3 and s4 are different
        System.out.println(s3==s4);     // false
        // If s3 and s4 point to different string objects, the output string will be different
        System.out.println(s3);         // helloworld
        System.out.println(s4);         // hello
    }
}

2.4 String Judgment Function (Member Method): Return value is boolean type

boolean equals(Object obj): Compare the contents of two strings to be the same, where the parameters can be subclass objects of any object;
Boolean equals IgnoreCase (String str): Compare the contents of two strings, ignore case;
boolean startsWith(String str): Determines whether a string object begins with the specified str;
boolean endsWith(String str): Determines whether a string object ends with the specified str.

2.5 String class acquisition function:

int length(): Gets the length of the string, which is the number of characters;
Char at (int index): Gets the character at the specified index, and the index value must exist, otherwise the index crossing exception will be reported.
int indexOf(String str): Gets the index of the first occurrence of the string STR in the string object. If it is not a single character, it returns the index of the first character in the str, if there is no return of -1;
String substring(int start): A substring truncated from the Start index to the end;
String substring(int start, int end): A substring from the Start index to the end index (not included).

Case study:

public class StringDemo3 {
    public static void main(String[] args) {
        String s = "HelloSomnus";

        // int length()
        System.out.println(s.length());

        // char charAt(int index)
        System.out.println(s.charAt(7));    // m
//      System. out. println (s. charAt (12); // java. lang. String IndexOutOfBoundsException exception

        // int indexOf(String str)
        System.out.println(s.indexOf("S")); //  5
        System.out.println(s.indexOf("Som"));   //  5 is the first index of str string initials
        System.out.println(s.indexOf("h")); //  -1 indicates that the string does not exist

        // String substring(int start)
        System.out.println(s.substring(5));     // Somnus
//      System. out. println (s. substring (13); / / / java. lang. String IndexOutOfBoundsException exception

        // String substring(int start, int end)
        System.out.println(s.substring(5, 8));  // Som, containing the start index, not the end index
    }
}

2.6 String's conversion function:

char[] toCharArray(): Converts strings to character arrays;
String to LowerCase (): Converts a string to a lowercase string;
String to UpperCase (): Converts strings to uppercase strings.

Case study:

public class StringDemo4 {
    public static void main(String[] args) {
        String s = "helloWorld";

        // char[] toCharArray()
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            System.out.println(chs[i]);
        }

        // String toLowerCase()
        String s1 = s.toLowerCase();
        System.out.println(s1);

        // String toUpperCase()
        String s2 = s.toUpperCase();
        System.out.println(s2);
    }
}

2.7H). Other functions of the String class:

String trim(): Remove the space at both ends of the string and return the string object.
String[] split(String str): A string is split according to the specified str, resulting in an array of strings.

Case study:

public class StringDemo5 {
    public static void main(String[] args) {
        String s = "aabbcc";
        String[] s1 = s.split("b");

        System.out.println(s1.length);

        for (int i = 0; i < s1.length; i++) {
            System.out.println(s1[i].length());
            System.out.println(s1[i]);
        }
    }
}

3. StringBulider class

3.1 Overview of StringBulider classes:

Is a variable length string, belonging to the string buffer class;
StringBulider is also a special type of reference data, which directly outputs the data in the object.

3.2 The difference between String and StringBuilder:

String content is fixed (once generated in a constant pool, it cannot be changed);
StringBuilder is a variable length string.
String is inefficient and wastes space when using + for string stitching.

3.3 StringBuilder construction method:

StringBuilder(): Construct a string generator without any characters, its initial capacity is 16 characters;
String Builder (String str): Constructs a string generator and initializes it to the specified string content.

3.4 StringBuilder member method:

public int capacity(): Returns the current capacity (theoretical capacity of the container). Capacity refers to the amount of storage that can be used for the latest insertion of characters, which needs to be reallocated.
public int length(): return length (number of characters), the number of characters stored;
Public StringBuilder append (any type): Append the parameter to the object after it is worth, and return it to itself;
public StringBuilder reverse(): Reverses its own character and returns it to itself.

3.5 Conversion between String and StringBuilder:

StringBuilder - > String: StringBuilder objects are converted to String objects through its toString method;
String - > String Builder: String objects can be obtained by String Builder's construction method.

Case study:

/*
 * StringBuilder:It is a variable length string and belongs to the string buffer class.
 * Construction method:
 *      StringBuilder():Construct a string generator without any characters, its initial capacity is 16 characters.
 *      StringBuilder(String str):Constructs a string generator and initializes it to the specified string content.
 * Membership methods:
 *      public int capacity():Returns the current capacity (theoretical capacity of the container). Capacity refers to the amount of storage that can be used for the latest insertion of characters, which needs to be reallocated.
 *      public int length():Returns the length (number of characters), the number of characters that have been stored.
 *      public StringBuilder append(Arbitrary Type: Append the parameter to the object and return it to itself.
 *      public StringBuilder reverse():Reverse your character and return it to itself.
 */
public class StringBuilderDemo {
    public static void main(String[] args) {
        // Spatial parameter construction method
        StringBuilder sb1 = new StringBuilder();
        System.out.println(sb1.capacity()); // Capacity allocated at 16 initialization
        System.out.println(sb1.length());   // Null character, representing the current absence of stored characters

        // A parametric constructor that sets the initial value to the specified string
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println(sb2.capacity()); // 21 represents the current capacity, there will always be 16 bytes of free space
        System.out.println(sb2.length());   // 5 Represents the number of characters currently stored

        // Public StringBuilder append (any type), the return value is itself, so it can be programmed in a chain.
        sb2.append("world");
        sb2.append(12.34);
        System.out.println(sb2);    // helloworld12.34
        sb2.append("somnus").append(3.14).append(true);
        System.out.println(sb2);    // helloworld12.34somnus3.14true

        // public StringBuilder reverse()
        sb2.reverse();
        System.out.println(sb2);    // eurt41.3sunmos43.21dlrowolleh
    }
}

Posted by esostigma on Wed, 12 Dec 2018 10:27:06 -0800