The use of Java API

1.[API]

1.1 API Overview

what is an API

API (Application Programming Interface): Application Programming Interface

API in java

Refers to the Java classes of various functions provided in the JDK. These classes encapsulate the underlying implementation. We don’t need to care about how these classes are implemented. We only need to learn how to use these classes. We can pass the help documentation. to learn how to use these APIs.

1.2 Specific use of API help documentation

​Open help file​​

​​Find the input box in the Index tab​​

​​Enter Random in the input box​​

​See which package the class is in​

​​See class description​​

​​Look at the construction method​​

​​See member methods​​

2. String class

2.1 String class overview

The String class represents strings, and all string literals (such as “abc”) in Java programs are implemented as instances of this class. That is, all double-quoted strings in a Java program are objects of the String class. The String class is under the java.lang package, so there is no need to import the package when using it!

2.2 Characteristics of the String class

Strings are immutable, their value cannot be changed after creation

Although String values ​​are immutable, they can be shared

Strings are effectively equivalent to character arrays (char[] ), but the underlying principle is byte arrays ( byte[] )

2.3 Constructor of String class

Common construction methods

sample code

public  class  StringDemo01 {
     public  static  void  main ( String[] args ) {
         //public String(): Create a blank string object with no content 
        String s1 = new String();
        System.out.println("s1:" + s1);

        //public String(char[] chs): Create a string object 
        char [] chs = { 'a' , 'b' , 'c' };
        String s2 = new String(chs);
        System.out.println("s2:" + s2);

        //public String(byte[] bys): Create a string object 
        byte [] bys = { 97 , 98 , 99 };
        String s3 = new String(bys);
        System.out.println("s3:" + s3);

        //String s = "abc"; Create a string object by direct assignment, the content is abc 
        String s4 = "abc" ;
        System.out.println("s4:" + s4);
    }
}

The specific execution results are as follows:

2.4 The difference between two ways of 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

A string given in “” mode, 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 The role of the == sign

Comparing primitive data types: comparing specific values

Compare reference data types: compare object address values

2.5.2 The role of the equals method

Method introduction

public  class  StringDemo02 {
     public  static  void  main ( String[] args ) {
         //Object 
        char [] chs = { 'a' , 'b' , 'c' };
        String s1 = new String(chs);
        String s2 = new String(chs);


        //Get the object String s3 = "abc" by direct assignment ;
        String s4 = "abc";

        //Compare the string object addresses are the same 
        System.out.println ( s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s3 == s4);
        System.out.println("--------");

        //Compare the string content is the same 
        System.out.println (s1.equals ( s2 ));
        System.out.println(s1.equals(s3));
        System.out.println(s3.equals(s4));
    }
}

sample code

/*
    Ideas:
        1: Know the username 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, use the for loop to achieve, and when the login is successful, use break to end the loop
 */ 
public  class  StringTest01 {
     public  static  void  main ( String[] args ) {
         // Know the username and password, define two strings to represent 
        String username = "itheima" ;
        String password = "czbk";

        //Use a loop to achieve multiple opportunities, the number of times here is clear, using a for loop to achieve, and when the login is successful, use break to end the loop 
        for ( int i= 0 ; i< 3 ; i++) {

            //Keyboard enter the username and password to log in, use Scanner to implement 
            Scanner sc = new Scanner(System. in );
 System.out 
            .println ( "Please enter user name: " );
            String name = sc.nextLine();

            System.out.println ( " Please enter your password:" );
            String pwd = sc.nextLine();

            //Compare the user name and password entered by the keyboard with the known user name and password, and give corresponding prompts. String content comparison, use the equals() method to implement 
            if (name. equals (username) && pwd. equals (password)) {System.out 
                .println ( "Login successful" );
                 break ;
            } else {
                if(2-i == 0) {System.out 
                    .println ( "Your account is locked, please contact your administrator" );
                } else {
                     //2,1,0 
                    //i,0,1,2 System.out 
                    .println ( "Login failed, you still have" + ( 2 - i) + "Chance" );
                }
            }
        }
    }
}

The specific execution results are as follows:

2.6 User login case

2.6.1 Case Requirements

If the 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.

2.6.2 Code Implementation

public  class  StringBuilderDemo01 {
     public  static  void  main ( String[] args ) {
         //public StringBuilder(): Create 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): According to the content of the string, create a variable string object 
        StringBuilder sb2 = new StringBuilder( "hello" );
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

The specific execution results are as follows:

2.8 See the common methods of String in the help document

3. StringBuilder class

3.1 StringBuilder class overview

StringBuilder is a variable string class, we can think of it as a container, the variable here refers to the content in the StringBuilder object is variable

3.2 Difference between StringBuilder class and String class

String class: content is immutable

StringBuilder class: content is mutable

3.3 Constructor of StringBuilder class

Common construction methods

sample code

public  class  StringBuilderDemo01 {
     public  static  void  main ( String[] args ) {
         //Create object 
        StringBuilder sb = new StringBuilder();
         //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);
    }
}

The specific execution results are as follows

3.4 StringBuilder class adding and reversing methods

sample code

public class StringBuilderDemo02 {
    public static void main(String[] args) {
        String s = sb.toString();
        System.out.println(s);
        String s = "hello";
        StringBuilder sb = new StringBuilder(s);
        System.out.println(sb);
    }
}

The specific execution results are as follows:

3.5 StringBuilder and String conversion

StringBuilder converts to String

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

String to StringBuilder

public StringBuilder(String s): Convert String to StringBuilder through the construction method

sample 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: Call the method and receive the result in a variable
        5: output result
 */ 
public  class  StringBuilderTest01 {
     public  static  void  main ( String[] args ) {
         //Define an array of int type, use static initialization to complete the initialization of array elements 
        int [] arr = { 1 , 2 , 3 };

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

        //Output the 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 
    /*
        Two clear: Return value type: String
            Parameters: int[] arr
     */ 
    public  static String arrayToString ( int [] arr ) {
         //Use StringBuilder in the method to concatenate as required, and convert the result to String and 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;
    }
}

The specific execution results are as follows:

3.6 Case of String Concatenation Upgraded Version

3.6.1 Case Requirements

Define a method to splicing the data in the int array into a string according to the specified format and return it, call the 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]

3.6.2 Code Implementation

/*
    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: Call the method and receive the result in a variable
        5: output result
 */ 
public  class  StringBuilderTest01 {
     public  static  void  main ( String[] args ) {
         //Define an array of int type, use static initialization to complete the initialization of array elements 
        int [] arr = { 1 , 2 , 3 };

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

        //Output the 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 
    /*
        Two clear: Return value type: String
            Parameters: int[] arr
     */ 
    public  static String arrayToString ( int [] arr ) {
         //Use StringBuilder in the method to concatenate as required, and convert the result to String and 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;
    }
}

The specific execution results are as follows:

3.7 Help document to view common methods of StringBuilder

4. Summary

In a word, I hope you will master the use of this API, this is just practice. When we use it to a certain extent, we will understand it. In fact, it is similar to a dictionary. If we don’t understand it, we can directly check it. Thank you for reading, like, favorite + follow! More java course learning routes, notes, interviews and other architectural materials, students who need it can privately message me (data) to get it for free!

Leave a Comment

Your email address will not be published. Required fields are marked *