Day08 - Common API s and String classes

Posted by njm on Sat, 25 Sep 2021 20:28:32 +0200

1.API

1.1 API overview [understanding]

  • What is an API
    API (Application Programming Interface): application programming interface
  • API in java
    It refers to the Java classes with various functions provided in the JDK. These classes encapsulate the underlying implementation. We don't need to care about how these classes work
    We only need to learn how to use these classes. We can learn how to use these API s through help documents.

1.2 how to use API help document [application]

  • Locate the input box in the index tab
  • Enter Random in the input box
  • See which package the class is in
  • Look at the description of the class
  • Look at the construction method
  • Look at member methods

2.String class

2.1 overview of string class [understanding]

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

2. Characteristics of 2string [understanding]

  • Strings are immutable and their values cannot be changed after creation
  • Although String values are immutable, they can be shared
  • String effect is equivalent to character array (char []), but the underlying principle is byte array (byte [])

2.3 construction method of string class [memory]

  • Common construction methods
  • Sample code
public class StringDemo01 {
public static void main(String[] args) {
//public String(): create a blank string object without any content
String s1 = new String();
System.out.println("s1:" + s1);
//public String(char[] chs): creates a string object according to the contents of the character array
char[] chs = {'a', 'b', 'c'};
String s2 = new String(chs);
System.out.println("s2:" + s2);
//Public string (byte [] bytes): creates a string object according to the contents of the byte array
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);
}
}

2.4 differences between the two methods of creating string objects [ understanding ]

  • Create by construction method
    For string objects created through new, each new will apply for a memory space. Although the contents are the same, the address values are different
  • Create by direct assignment
    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 string comparison [understanding]

2.5.1 function of = = sign

  • Compare basic data types: specific values are compared
  • Compare reference data types: object address values are compared

2.5.2 functions of equals method

  • Method introduction
public boolean equals(String s) Compare whether the contents of two strings are the same and case sensitive
  • Sample code
public class StringDemo02 {
public static void main(String[] args) {
//Get the object by constructing the method
char[] chs = {'a', 'b', 'c'};
String s1 = new String(chs);
String s2 = new String(chs);
//Get the object by direct assignment
String s3 = "abc";
String s4 = "abc";
//Compare whether the address of the string object is the same
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s3 == s4);
System.out.println("--------");
//Compare whether the string contents are the same
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s3.equals(s4));
}
}

2.6 user login case [application]

2.6.1 case requirements

Known user name and password, please use the program to simulate user login. Give a total of three opportunities. After logging in, give corresponding prompts

2.6.2 code implementation

/*
Idea:
1:If the user name and password are known, define two string representations
2:Enter the user name and password to log in with the keyboard, which is implemented with Scanner
3:Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt. Compare the contents of the string with
equals() Method implementation
4:Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use break to end the loop
*/
public class StringTest01 {
public static void main(String[] args) {
//If the user name and password are known, define two string representations
String username = "itheima";
String password = "czbk";
//Use the loop to realize multiple opportunities. The number of times here is clear. Use the for loop to realize it. When the login is successful, use break to end the loop
for(int i=0; i<3; i++) {
//Enter the user name and password to log in with the keyboard, which is implemented with Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Please enter user name:");
String name = sc.nextLine();
System.out.println("Please input a password:");
String pwd = sc.nextLine();
//Compare the user name and password entered on the keyboard with the known user name and password, and give the corresponding prompt. Compare the contents of the string,
use equals() Method implementation
if (name.equals(username) && pwd.equals(password)) {
System.out.println("Login succeeded");
break;
} else {
if(2-i == 0) {
System.out.println("Your account is locked. Please contact the administrator");
} else {
//2,1,0
//i,0,1,2
System.out.println("Login failed, you still have" + (2 - i) + "Second chance");
}
}
}
}
}

2.7 traversal string case [ application ]

2.7.1 case requirements

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

2.7.2 code implementation

/*
Idea:
1:Enter a string on the keyboard and implement it with Scanner
2:To traverse a string, you must first be able to get each character in the string
public char charAt(int index): Returns the char value at the specified index, and the index of the string starts from 0
3:Traverse the string, and then get the length of the string
public int length(): Returns the length of this string
 length of array: array name. length
 Length of string: String object. length()
4:General format of traversal string
*/
public class StringTest02 {
public static void main(String[] args) {
//Enter a string on the keyboard and implement it with Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string:");
String line = sc.nextLine();
for(int i=0; i<line.length(); i++) {
System.out.println(line.charAt(i));
}
}
}

2.8 case of counting the number of characters [ application ]

2.8.1 case requirements

Enter a string on the keyboard and count the occurrence times of uppercase, lowercase and numeric characters in the string (other characters are not considered)

2.8.2 code implementation

/*
Idea:
1:Enter a string on the keyboard and implement it with Scanner
2:To count the number of three types of characters, you need to define three statistical variables with initial values of 0
3:Traverse the string to get each character
4:Judge which type the character belongs to, and then the corresponding type of statistical variable + 1
 If ch is a character, I want to judge whether it belongs to uppercase letters, lowercase letters or numbers, and directly judge whether the character is in the corresponding range
 Just surround
 Capital letters: ch > ='a '& & ch < ='z'
Lowercase letters: ch > ='a '& & ch < ='z'
Number: ch > ='0 '& & ch < ='9'
5:Output the number of characters of three types
*/
public class StringTest03 {
public static void main(String[] args) {
//Enter a string on the keyboard and implement it with Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string:");
String line = sc.nextLine();
//To count the number of three types of characters, you need to define three statistical variables with initial values of 0
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
//Traverse the string to get each character
for(int i=0; i<line.length(); i++) {
char ch = line.charAt(i);
//Judge which type the character belongs to, and then the corresponding type of statistical variable + 1
if(ch>='A' && ch<='Z') {
bigCount++;
} else if(ch>='a' && ch<='z') {
smallCount++;
} else if(ch>='0' && ch<='9') {
numberCount++;
}
}
//Output the number of characters of three types
System.out.println("capital:" + bigCount + "individual");
System.out.println("Lowercase letters:" + smallCount + "individual");
System.out.println("Number:" + numberCount + "individual");
}
}

2.9 string splicing case [application]

2.9.1 case requirements

Define a method to splice the data in the int array into a string according to the specified format, call the method, and output the result on the console. For example, the array is int[] arr = {1,2,3}, The output result after executing the method is: [1, 2, 3]

2.9.2 code implementation

/*
Idea:
1:Define an array of type int, and use static initialization to complete the initialization of array elements
2:Defines a method for splicing the data in the int array into a string according to the specified format.
Return value type String, parameter list int[] arr
3:Traverse the array in the method and splice it as required
4:Call the method to receive the result with a variable
5:Output results
*/
public class StringTest04 {
public static void main(String[] args) {
//Define an array of type int, and use static initialization to complete the initialization of array elements
int[] arr = {1, 2, 3};
//Call the method to receive the result with a variable
String s = arrayToString(arr);
//Output results
System.out.println("s:" + s);
}
//Defines a method for splicing the data in the int array into a string according to the specified format
/*
Two clear:
Return value type: String
 Parameter: int[] arr
*/
public static String arrayToString(int[] arr) {
//Traverse the array in the method and splice it as required
String s = "";
s += "[";
for(int i=0; i<arr.length; i++) {
if(i==arr.length-1) {
s += arr[i];
} else {
s += arr[i];
s += ", ";
}
}
s += "]";
return s;
}
}

2.10 string inversion case [application]

2.10.1 case requirements

Define a method to realize string inversion. Enter a string on the keyboard, call this method, and output the result on the console
For example, enter abc on the keyboard and output the result cba

2.10.2 code implementation

/*
Idea:
1:Enter a string on the keyboard and implement it with Scanner
2:Define a method to realize String inversion. Return value type String, parameter String s
3:In the method, the string is traversed backwards, and then each obtained character is spliced into a string and returned
4:Call the method to receive the result with a variable
5:Output results
*/
public class StringTest05 {
public static void main(String[] args) {
//Enter a string on the keyboard and implement it with Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string:");
String line = sc.nextLine();
//Call the method to receive the result with a variable
String s = reverse(line);
//Output results
System.out.println("s:" + s);
}
//Define a method to realize string inversion
/*
Two clear:
Return value type: String
 Parameter: String s
*/
public static String reverse(String s) {
//In the method, the string is traversed backwards, and then each obtained character is spliced into a string and returned
String ss = "";
for(int i=s.length()-1; i>=0; i--) {
ss += s.charAt(i);
}
return ss;
}
}

2.11 common methods for viewing String in help documents [ memory ]

3.StringBuilder class

3.1 overview of StringBuilder class [understanding]

StringBuilder is a variable string class. We can regard it as a container. The variable here refers to the string in the StringBuilder object
The content is variable

3. Differences between 2stringbuilder class and String class [understanding]

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

3.3 construction method of StringBuilder class [memory]

  • Common construction methods
  • Sample code
public class StringBuilderDemo01 {
public static void main(String[] args) {
//public StringBuilder(): creates a blank variable string object without any content
StringBuilder sb = new StringBuilder();
System.out.println("sb:" + sb);
System.out.println("sb.length():" + sb.length());
//public StringBuilder(String str): creates a variable string object according to the contents of the string
StringBuilder sb2 = new StringBuilder("hello");
System.out.println("sb2:" + sb2);
System.out.println("sb2.length():" + sb2.length());
}
}

3.4StringBuilder class addition and inversion method [memory]

  • Add and reverse methods
  • Sample code
public class StringBuilderDemo01 {
public static void main(String[] args) {
//create object
StringBuilder sb = new StringBuilder();
//Public StringBuilder append (any type): adds data and returns 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 opposite character sequence
sb.reverse();
System.out.println("sb:" + sb);
}
}

3.5 conversion between StringBuilder and String [ application ]

  • Convert StringBuilder to String
    public String toString(): you can convert StringBuilder to String through toString()
  • Convert String to StringBuilder
    public StringBuilder(String s): you can convert a String into a StringBuilder by constructing a 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(): Through toString(), you can convert StringBuilder to
String
String s = sb.toString();
System.out.println(s);
*/
//Convert String to StringBuilder
String s = "hello";
//StringBuilder sb = s; // This is wrong
//public StringBuilder(String s): you can convert a String to a String by constructing a method
StringBuilder
StringBuilder sb = new StringBuilder(s);
System.out.println(sb);
}
}

3.6 string splicing upgrade case [application]

3.6.1 case requirements

Define a method to splice the data in the int array into a string according to the specified format, call the method, and output the result on 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

/*
Idea:
1:Define an array of type int, and use static initialization to complete the initialization of array elements
2:Defines a method for splicing the data in the int array into a string according to the specified format.
Return value type String, parameter list int[] arr
3:In the method, use StringBuilder to splice as required, and convert the result into String to return
4:Call the method to receive the result with a variable
5:Output results
*/
public class StringBuilderTest01 {
public static void main(String[] args) {
//Define an array of type int, and use static initialization to complete the initialization of array elements
int[] arr = {1, 2, 3};
//Call the method to receive the result with a variable
String s = arrayToString(arr);
//Output results
System.out.println("s:" + s);
}
//Defines a method for splicing the data in the int array into a string according to the specified format
/*
Two clear:
Return value type: String
 Parameter: int[] arr
*/
public static String arrayToString(int[] arr) {
//In the method, use StringBuilder to splice as required, and convert the result into String to 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;
}
}

3.7 string inversion upgrade case [application]

3.7.1 case requirements

Define a method to realize string inversion. Enter a string on the keyboard, call this method, and output the result on the console
For example, enter abc on the keyboard and output the result cba

3.7.2 code implementation

/*
Idea:
1:Enter a string on the keyboard and implement it with Scanner
2:Define a method to realize String inversion. Return value type String, parameter String s
3:In the method, use StringBuilder to reverse the String, and convert the result into String to return
4:Call the method to receive the result with a variable
5:Output results
*/
public class StringBuilderTest02 {
public static void main(String[] args) {
//Enter a string on the keyboard and implement it with Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string:");
String line = sc.nextLine();
//Call the method to receive the result with a variable
String s = myReverse(line);
//Output results
System.out.println("s:" + s);
}
//Define a method to realize String inversion. Return value type String, parameter String s
/*
Two clear:
Return value type: String
 Parameter: String s
*/
public static String myReverse(String s) {
//In the method, use StringBuilder to reverse the String, and convert the result into String to return
//String --- StringBuilder --- reverse() --- String
// StringBuilder sb = new StringBuilder(s);
// sb.reverse();
// String ss = sb.toString();
// return ss;
return new StringBuilder(s).reverse().toString();
}
}

3.8 help document viewing StringBuilder common methods [memory]

Topics: Java