Commonly used API s in Java

1.API

1.1 API Overview - Use of Help Documentation

  • what is an API

    ​ API (Application Programming Interface): Application Programming Interface

  • API in java

    What we mean is the Java classes for the various functions provided in the JDK that encapsulate the underlying implementation. We don't need to care how these classes are implemented. We just need to learn how these classes are used. We can help Documentation to learn how to use these APIs.

How to use the API help documentation :

  • Open help document

  • Find the input box in the Index tab

  • Enter Random in the input box

  • See which package the class is in

  • see class description

  • see construction method

  • see member method

1.2 Keyboard input string

Scanner class:

​ next() : When a space is encountered, no more data will be entered. End tag: space, tab key

​ nextLine() : The data can be received completely, end tag: carriage return line feed

Code :

package com.itheima.api;

import java.util.Scanner;

public class Demo1Scanner {
    /*
        next() : If a space is encountered, the data will no longer be entered.

                End tag: space, tab key

        nextLine() : Data can be received in full

                Closing tag: carriage return line feed
     */
    public static void main(String[] args) {
        // 1. Create a Scanner object
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter:");
        // 2. Call the nextLine method to receive the string
        // ctrl + alt + v : Quickly generate the return value of the method
        String s = sc.nextLine();

        System.out.println(s);
    }
}

package com.itheima.api;

import java.util.Scanner;

public class Demo2Scanner {
    /*
        nextInt When used in conjunction with the nextLine method, the nextLine method has no opportunity for keyboard entry.

        Suggestion: When inputting data by keyboard in the future, if the string and integer are accepted together, it is recommended to use the next method to accept the string.
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter an integer:");
        int num = sc.nextInt(); // 10 + carriage return line feed
        System.out.println("Please enter a string:");
        String s = sc.nextLine();


        System.out.println(num);
        System.out.println(s);
    }
}

2. String class

2.1 String overview

​ 1 The String class is under the java.lang package, so there is no need to import the package when using it

2 The String class represents strings, and all string literals (such as "abc") in a Java program are implemented as instances of this class. That is, all double-quoted strings in a Java program are objects of the String class

​ 3 Strings are immutable, their value cannot be changed after creation

2.2 Constructor of String class

Common construction methods

[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-PDeXlktJ-1660128164067)(.\img\1590939947722.png)]

sample code

package com.itheima.string;

public class Demo2StringConstructor {
    /*
        String Common constructors of classes:

            public String() : Creates an empty string object with nothing in it
            public String(char[] chs) : Create a string object from the contents of a character array
            public String(String original) : Create a string object based on the incoming string content
            String s = "abc";  Create a string object by direct assignment, the content is abc

         Notice:
                String This class is special. When printing its object name, the memory address will not appear.
                Rather, it is the actual content recorded by the object.

                Object Orientation - Inheritance, Object class
     */
    public static void main(String[] args) {
        // public String() : Creates an empty string object with no content
        String s1 = new String();
        System.out.println(s1);

        // public String(char[] chs) : Create a string object based on the content of the character array
        char[] chs = {'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2);

        // public String(String original) : Create a string object based on the incoming string content
        String s3 = new String("123");
        System.out.println(s3);
    }
}

2.4 Comparison of differences in creating string objects

  • Created by constructor

    ​ A string object created by new will apply for a memory space each time new, although the content is the same, but the address value is different

  • Create by direct assignment

    ​ For a string given in the form of "", as long as the character sequence is the same (order and case), no matter how many times it appears in the program code, the JVM will only create a String object and maintain it in the string pool

2.5 Comparison of strings

2.5.1 String comparison

  • == compares primitive data types: compares concrete values
  • == compares reference data types: compares object address values

String class: public boolean equals(String s) Compares whether the contents of two strings are the same, case-sensitive

Code :

package com.itheima.stringmethod;

public class Demo1Equals {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = "ABC";
        String s3 = "abc";

        // equals : compare string contents, case sensitive
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));

        // equalsIgnoreCase : Compare string contents, ignoring case
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}

2.6 User Login Case [Application]

Case requirements :

​ Know the user name and password, please use the program to simulate user login. A total of three chances are given. After logging in, a corresponding prompt will be given.

**implementation steps: **

  1. Know the user name and password, define two strings to represent
  2. Enter the user name and password to log in with the keyboard, use Scanner to achieve
  3. Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts.
  4. String content comparison, implemented with equals() method
  5. Use the loop to achieve multiple opportunities, the number of times here is clear, use the for loop to achieve, and when the login is successful, use break to end the loop

Code :

package com.itheima.test;

import java.util.Scanner;

public class Test1 {
    /*
        Requirements: User name and password are known, please use the program to simulate user login.
              A total of three chances are given. After logging in, a corresponding prompt will be given.

        Ideas:
        1. Know the user name and password, define two strings to represent
        2. Enter the user name and password to log in with the keyboard, use Scanner to achieve
        3. Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts.
            String content comparison, implemented with equals() method
        4. Use the loop to achieve multiple opportunities, the number of times here is clear, using for loop to achieve, and when the login is successful, use break to end the loop

     */
    public static void main(String[] args) {
        // 1. Know the username and password, define two strings to represent
        String username = "admin";
        //String password = "123456";
        // 2. Enter the user name and password to log in with the keyboard, and use Scanner to realize
        Scanner sc = new Scanner(System.in);
        // 4. Use loops to achieve multiple opportunities, where the number of times is clear, using for loops to achieve
        for(int i = 1; i <= 3; i++){
            System.out.println("please enter user name:");
            String scUsername = sc.nextLine();
            System.out.println("Please enter password:");
            String scPassword = sc.nextLine();
            // 3. Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts.
            if(username.equals(scUsername) && password.equals(scPassword)){
                System.out.println("login successful");
                break;
            }else{
                if(i == 3){
                    System.out.println("You have reached the limit of today's logins, Please come again tomorrow");
                }else{
                    System.out.println("Login failed,you have leftovers" + (3-i) +"next chance");
                }

            }
        }

    }
}

2.7 Traverse String Case [Application]

Case requirements :

​ Enter a string on the keyboard, and use the program to traverse the string on the console

Implementation steps:

  1. Keyboard input a string, implemented with Scanner
  2. Traverse the string, first of all, you must be able to get each character in the string, public char charAt(int index): return the char value at the specified index, the index of the string also starts from 0
  3. Traverse the string, and then get the length of the string, public int length(): returns the length of the string
  4. traverse print

Code :

package com.itheima.test;

import java.util.Scanner;

public class Test2 {
    /*
        Requirement: Enter a string on the keyboard, and use the program to traverse the string on the console

        Ideas:
        1. Keyboard input a string, implemented with Scanner
        2. Traverse the string, first to be able to get each character in the string
            public char charAt(int index): Returns the char value at the specified index, the index of the string also starts from 0
        3. Traverse the string, and then get the length of the string
            public int length(): returns the length of this string
        4. traverse print
9
     */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter:");
        String s = sc.nextLine();
        // 2. Traverse the string, first of all to be able to get each character in the string
        for(int i = 0; i < s.length(); i++){
            // i : each index of the string
            char c = s.charAt(i);
            System.out.println(c);
        }
    }
}

2.8 Case of counting the number of characters [Application]

Case requirements :

​ Enter a string on the keyboard, and use the program to traverse the string on the console

Implementation steps:

  1. Keyboard input a string, implemented with Scanner
  2. Split the string into a character array, public char[] toCharArray( ): Split the current string into a character array and return
  3. iterate over characters

Code :

package com.itheima.test;

import java.util.Scanner;

public class Test3 {
    /*
       Requirement: Enter a string on the keyboard, and use the program to traverse the string on the console

       Ideas:
       1. Keyboard input a string, implemented with Scanner
       2. Split string into character array
                public char[] toCharArray( ): Split the current string into a character array and return
       3. iterate over character array

    */
    public static void main(String[] args) {
        //  1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter:");
        String s = sc.nextLine();
        // 2. Split string into character array
        char[] chars = s.toCharArray();
        // 3. Traverse the character array
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
    }
}

2.9 Mobile phone number shielding - string interception

Case requirements :

​ Accept a mobile phone number from the keyboard in the form of a string, mask the middle four digits
​ The final effect is: 156****1234

Implementation steps:

  1. Keyboard input a string, implemented with Scanner
  2. Intercept the first three characters of the string
  3. Truncate the last four digits of the string
  4. Concatenate the two intercepted strings with **** in the middle, and output the result

Code :

package com.itheima.test;

import java.util.Scanner;

public class Test5 {
    /*
        Requirement: Accept a mobile phone number from the keyboard in the form of a string, mask the middle four digits
        The final effect is: 156****1234

        Ideas:
        1. Keyboard input a string, implemented with Scanner
        2. Intercept the first three characters of the string
        3. Truncate the last four digits of the string
        4. Concatenate the two intercepted strings with **** in the middle, and output the result

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter phone number:");
        String telString = sc.nextLine();
        // 2. Intercept the first three characters of the string
        String start = telString.substring(0,3);
        // 3. Truncate the last four digits of the string
        String end = telString.substring(7);
        // 4. Concatenate the two intercepted strings with **** in the middle, and output the result
        System.out.println(start + "****" + end);
    }
}

2.10 Sensitive word replacement - string replacement

Case requirements :

​ Keyboard input a string, if the string contains (TMD), use *** to replace

Implementation steps:

  1. Keyboard input a string, implemented with Scanner
  2. Replace sensitive words
    String replace(CharSequence target, CharSequence replacement)
    Replace the target content in the current string with replacement and return a new string
  3. output result

Code :

package com.itheima.test;

import java.util.Scanner;

public class Test6 {
    /*
        Requirement: Enter a string on the keyboard, if the string contains (TMD), use *** to replace

        Ideas:
        1. Keyboard input a string, implemented with Scanner
        2. Replace sensitive words
                String replace(CharSequence target, CharSequence replacement)
                Replace the target content in the current string with replacement and return a new string
        3. output result

     */
    public static void main(String[] args) {
        // 1. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter:");
        String s = sc.nextLine();
        // 2. Replace sensitive words
        String result = s.replace("TMD","***");
        // 3. Output the result
        System.out.println(result);
    }
}

2.11 Cutting Strings

Case requirements :

​ Enter student information from the keyboard in the form of a string, for example: "Zhang San, 23"

​ Cut out valid data from the string and encapsulate it as a Student object

Implementation steps:

  1. Write the Student class to encapsulate data

  2. Keyboard input a string, implemented with Scanner

  3. Cut the string according to the comma to get (Zhang San)(23)

    String[] split(String regex) : Cut according to the incoming string as a rule
    Store the cut content in a string array and return the string array

  4. Take out the element content from the obtained string array and encapsulate it as an object through the parameterized construction method of the Student class

  5. Call the object getXxx method, take out the data and print.

Code :

package com.itheima.test;

import com.itheima.domain.Student;

import java.util.Scanner;

public class Test7 {
    /*
         Requirement: Enter student information from the keyboard in the form of a string, for example: "Zhang San, 23"
                Cut out valid data from the string and encapsulate it as a Student object
         Ideas:
            1. Write the Student class to encapsulate data
            2. Keyboard input a string, implemented with Scanner
            3. Cut the string according to the comma to get (Zhang San)(23)
                    String[] split(String regex) : Cut according to the incoming string as a rule
                    Store the cut content in a string array and return the string array
            4. Take out the element content from the obtained string array and encapsulate it as an object through the parameterized construction method of the Student class
            5. Call the object getXxx method, take out the data and print.

     */
    public static void main(String[] args) {
        // 2. Enter a string on the keyboard and implement it with Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter student information:");
        String stuInfo = sc.nextLine();
        // stuInfo = "Zhangsan,23";
        // 3. Cut the string according to the comma to get (Zhang San) (23)
        String[] sArr = stuInfo.split(",");

//        System.out.println(sArr[0]);
//        System.out.println(sArr[1]);

        // 4. Take out the element content from the obtained string array and encapsulate it as an object through the parameterized construction method of the Student class
        Student stu = new Student(sArr[0],sArr[1]);

        // 5. Call the object getXxx method, take out the data and print it.
        System.out.println(stu.getName() + "..." + stu.getAge());
    }
}

2.12 Summary of String methods

Common methods of String class:

​ public boolean equals(Object anObject) Compare the contents of strings, strictly case-sensitive

​ public boolean equalsIgnoreCase(String anotherString) Compare the contents of strings, ignoring case

​ public int length() returns the length of this string

​ public char charAt(int index) returns the char value at the specified index

​ public char[] toCharArray() Returns after splitting the string into a character array

​ public String substring(int beginIndex, int endIndex) Intercept according to the start and end indexes to get a new string (including the head, excluding the tail)

​ public String substring(int beginIndex) Intercept from the incoming index, intercept to the end, and get a new string

​ public String replace(CharSequence target, CharSequence replacement) Use the new value to replace the old value in the string to get a new string

​ public String[] split(String regex) Cut the string according to the incoming rules to get a string array

3 StringBuilder class

3.1 Overview of the StringBuilder class

​ Overview: StringBuilder is a mutable string class, we can think of it as a container, where mutable means that the content in the StringBuilder object is mutable

3.2 The difference between the StringBuilder class and the String class

  • **String class:** content is immutable
  • **StringBuilder class:** content is mutable

3.3 Constructor of StringBuilder class

Common construction methods

method nameillustrate
public StringBuilder()Creates a blank mutable string object with nothing in it
public StringBuilder(String str)Create a mutable string object based on the content of the string

sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //public StringBuilder(): Creates a blank mutable string object with no content
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());

        //public StringBuilder(String str): Create a variable string object based on the content of the string
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

3.4 Common member methods of StringBuilder

  • Add and reverse methods

    method nameillustrate
    public StringBuilder append( any type)add data, and return the object itself
    public StringBuilder reverse()Returns the reversed sequence of characters
  • sample code

public class StringBuilderDemo01 {
    public static void main(String[] args) {
        //create object
        StringBuilder sb = new StringBuilder();

        //public StringBuilder append (any type): add data and return the object itself
//        StringBuilder sb2 = sb.append("hello");
//
//        System.out.println("sb:" + sb);
//        System.out.println("sb2:" + sb2);
//        System.out.println(sb == sb2);

//        sb.append("hello");
//        sb.append("world");
//        sb.append("java");
//        sb.append(100);

        //chain programming
        sb.append("hello").append("world").append("java").append(100);

        System.out.println("sb:" + sb);

        //public StringBuilder reverse(): returns the reverse sequence of characters
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

3.5 Mutual conversion between StringBuilder and String [Application]

  • Convert StringBuilder to String

    ​ public String toString(): Convert StringBuilder to String through toString()

  • Convert String to StringBuilder

    ​ public StringBuilder(String s): Converting String to StringBuilder can be achieved through the construction method

  • sample code

public class StringBuilderDemo02 {
    public static void main(String[] args) {
        /*
        //StringBuilder Convert to String
        StringBuilder sb = new StringBuilder();
        sb.append("hello");

        //String s = sb; //this is wrong

        //public String toString(): Convert StringBuilder to String through toString()
        String s = sb.toString();
        System.out.println(s);
        */

        //String to StringBuilder
        String s = "hello";

        //StringBuilder sb = s; //This is wrong

        //public StringBuilder(String s): Convert String to StringBuilder through the construction method
        StringBuilder sb = new StringBuilder(s);

        System.out.println(sb);
    }
}

3.6 StringBuilder splicing string case

Case requirements :

​ Define a method to splicing the data in the int array into a string according to the specified format and return, call this method,

​ and output the result in the console. For example, the array is int[] arr = {1,2,3}; , the output result after executing the method is: [1, 2, 3]

Implementation steps:

  1. Define an array of type int and use static initialization to initialize the elements of the array
  2. Define a method for splicing the data in the int array into a string according to the specified format and returning it.
    Return value type String, parameter list int[] arr
  3. Use StringBuilder in the method to splicing as required, and convert the result to String for return
  4. Invoke a method and receive the result in a variable
  5. output result

Code :

/*
    Ideas:
        1:Define an array of type int and use static initialization to initialize the elements of the array
        2:Define a method for splicing the data in the int array into a string according to the specified format and returning it.
          Return value type String, parameter list int[] arr
        3:Use StringBuilder in the method to splicing as required, and convert the result to String for return
        4:Invoke a method and receive the result in a variable
        5:output result
 */
public class StringBuilderTest01 {
    public static void main(String[] args) {
        //Define an array of type int and use static initialization to initialize the elements of the array
        int[] arr = {1, 2, 3};

        //Invoke a method and receive the result in a variable
        String s = arrayToString(arr);

        //output result
        System.out.println("s:" + s);

    }

    //Define a method for splicing the data in the int array into a string according to the specified format and returning it
    /*
        Two clear:
            Return value type: String
            Parameters: int[] arr
     */
    public static String arrayToString(int[] arr) {
        //Use StringBuilder in the method to splicing as required, and convert the result to String for return
        StringBuilder sb = new StringBuilder();

        sb.append("[");

        for(int i=0; i<arr.length; i++) {
            if(i == arr.length-1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }

        sb.append("]");

        String s = sb.toString();

        return  s;
    }
}

Tags: Java jvm programming language

Posted by iblackedout on Fri, 16 Sep 2022 02:03:45 +0930