[Java foundation] 09 "common API

Keywords: Java Programming JDK IntelliJ IDEA

API overview

API concept

API(Application Programming Interface): application programming interface

Also known as: help documents

To write a robot program to control the robot to play football, the program needs to send all kinds of commands to the robot, such as running forward, running backward, shooting, grabbing the ball, etc. It's hard for anyone who hasn't written a program to imagine how to write such a program. But for experienced developers, knowing that robot manufacturers will provide some Java classes for controlling robots, these classes define the methods to operate various robot actions. In fact, these Java classes are the interfaces provided by robot manufacturers for application programming. We call these classes API. The Java API in this chapter refers to the Java classes of various functions provided in the JDK

Quick API steps:

A: Open help document

B: Click display, find index and see input box

C: If you want to learn something, you can type it in the box

Example: Random

D: look at the bag.

Classes under the java.lang package do not need to import packages when they are used

E: Look at the description of the class

The Random class is a class for generating Random numbers

F: On the construction method

Random(): nonparametric construction method

​ Random r = new Random();

G: See member method

public int nextInt(int n): generates a random number in the range of [0,n)

Call method:

Look at the type of return value: you can receive the type returned by others

Look at the method name: don't write the name wrong

Look at the formal parameters: if someone wants several parameters, you can give them to them. If they want any data type, you can give them to them

​ int number = r.nextInt(100);

Scanner class and Object class

Class Scanner

Scanner class function

The method of Scanner class can be used to receive the data input by keyboard, and the received data types are basic data type and string type

The Scanner class accepts strings entered by the keyboard

Scanner: used to get keyboard input data. (basic data type, string data)

public String nextLine(): get the string data entered by keyboard

import java.util.Scanner;
public class ScannerDemo {
	public static void main(String[] args) {
		//Create keyboard entry object
		Scanner sc = new Scanner(System.in);
		
		//receive data
		System.out.println("Please enter a string data:");
		String line = sc.nextLine();
		
		//Output result
		System.out.println("line:"+line);
	}

}

Class Object

Object class function

The java.lang.Object class is the root class in the Java language, that is, the parent class of all classes. All method subclasses described in it are available. When an Object is instantiated, the ultimate parent is Object.

If a class does not specifically specify a parent class, it inherits from the Object class by default. For example:

public class MyClass /*extends Object*/ {
  	// ...
}

According to the JDK source code and the API documents of the Object class, the Object class contains 11 methods. Two of them:

  • public String toString(): returns the string representation of the object.
  • public boolean equals(Object obj): indicates whether another object is "equal" to this object.

toString() method of Object class

Method summary

  • public String toString(): returns the string representation of the object.

toString method returns the string representation of the object. In fact, the content of the string is the type + @ + memory address value of the object.

Because the result returned by toString method is memory address, in development, it is often necessary to get the corresponding string representation according to the object's properties, so it also needs to be rewritten.

Overwrite

If you do not want to use the default behavior of the toString method, you can override it. For example, a custom Student class:

Student class

public class Student {
	private String name;
	private int age;
	
	public Student() {}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	

}

Object: is the root class of the class hierarchy. All classes directly or indirectly inherit from this class.
Construction method: Object()

Output the object name directly. The output bottom layer calls toString()

Looking at the API, we found that it is recommended that all subclasses override toString().
How to rewrite this method? It can be generated automatically.

In IntelliJ IDEA, you can click Generate... In the Code menu, or you can use the shortcut key alt+insert and click toString() option. Select the member variables to include and confirm.

Tip: when we directly use the output statement to output the object name, we actually call its toString() method through the object.

public class ObjectDemo {
	public static void main(String[] args) {
		Student s = new Student();
		s.setName("Brigitte Lin");
		s.setAge(30);
		System.out.println(s);
		//System.out.println(s.toString());
		/*
		 public void println(Object x) { //Object x = s;
	        String s = String.valueOf(x);
	        synchronized (this) {
	            print(s);
	            newLine();
	        }
	    }
	    
	    public static String valueOf(Object obj) { //Object obj = x;
        	return (obj == null) ? "null" : obj.toString();
    	}
	    */
	}

}

equals() method of Object class

Method summary

  • public boolean equals(Object obj): indicates whether another object is "equal" to this object.

Call the member method equals and specify another object as the parameter to determine whether the two objects are the same. There are two ways of "same" here: default and custom.

Default address comparison

If the equal method is not overridden and overridden, the Object address comparison of = = operator is performed by default in the Object class. As long as it is not the same Object, the result must be false.

Object content comparison

If you want to compare the contents of an object, that is, if all or some of the specified member variables are the same, you can override the equals method. For example:

Rewrite equals method in student class

@Override
public boolean equals(Object obj) {
	//s1.equals(s2)
	//this -- s1
	//obj -- s2
	
	if (this == obj)
		return true;
	if (obj == null)
		return false;
	//Compare whether the object is an object of the same class
	if (getClass() != obj.getClass())
		return false;
	Student other = (Student) obj; //other -- s2
	if (age != other.age) //this.age -- s1.age
		return false;
	if (name == null) {
		if (other.name != null)
			return false;
	} else if (!name.equals(other.name))
		//equals() of a string compares whether the contents of the string are the same
		return false;
	return true;
}

==: you can compare basic data types. When comparing basic data types, you can compare whether the values of basic data types are the same or whether the address values of reference data types are the same

What we want to compare now is whether the content of the object is the same? What should we do?

By looking at the API, we found a way to compare whether objects are equal:

public boolean equals(Object obj)

By default, the equals() method in the Object class compares whether the address of the Object is the same.

If we want to compare whether the contents of objects are the same, we have to rewrite the method ourselves.

How to override this method?

Automatically generated. This Code fully considers the problems of empty object and consistent type, but the method content is not unique. Most ides can automatically Generate Code content for equals methods. In IntelliJ IDEA, you can use Generate Option, you can also use the shortcut key alt+insert and select equals() and hashCode() for automatic Code generation. :

public class ObjectDemo {
	public static void main(String[] args) {
		Student s1 = new Student("Brigitte Lin", 30);
		Student s2 = new Student("Brigitte Lin", 30);
		
		//System.out.println(s1 == s2);//false
		
		System.out.println(s1.equals(s2));//false
		/*
	    public boolean equals(Object obj) {
	    	//this -- s1
	    	//obj -- s2
	        return (this == obj);
	    }
	    */
	}

}

Class String

String class overview

View the description of String class through the API provided by JDK

A:"abc" is an instance of String class or an object of String class

B: The string literal "abc" can also be regarded as a string object

C: A string is a constant, once assigned, it cannot be changed

D: String is essentially an array of characters

The construction method of String class

String(String original): encapsulate string data into string objects

String(char[] value): encapsulate the data of character array into string object

String(char[] value, int index, int count): encapsulate part of the data of character array into string object

Demonstration of common construction methods

String: represents a string class.
A string of data consisting of more than one character.
The essence of a string is an array of characters.

Construction method:
String(String original): encapsulate string data into string objects
String(char[] value): encapsulate the data of character array into string object
String(char[] value, int index, int count): encapsulate part of the data of character array into string object

public String toString(): returns the object itself (it is already a string)

public class StringDemo {
	public static void main(String[] args) {
		//String(String original): encapsulate string data into string objects
		String s1 = new String("hello");
		System.out.println(s1);
		System.out.println("----------");
		
		//String(char[] value): encapsulate the data of character array into string object
		char[] value = {'h','e','l','l','o'};
		String s2 = new String(value);
		System.out.println(s2);
		System.out.println("----------");
		
		//String(char[] value, int index, int count): encapsulate part of the data of character array into string object
		//String s3 = new String(value,0,value.length);
		String s3 = new String(value,0,3);
		System.out.println(s3);
		System.out.println("----------");
		
		//Most commonly used
		String s4 = "hello";
		System.out.println(s4);
	}

}

The difference between two ways of creating string objects

Characteristics of creating objects with String class:
A: Creating objects through construction methods
B: Creating objects by direct assignment
There is a difference between the two methods.
The string object created by the constructor is in heap memory.
The string object created by direct assignment is a constant pool in the method area.

public static void main(String[] args) {
  String s1 = new String("hello");
  String s2 = new String("hello");
  
  String s3 = "hello";
  String s4 = "hello";
  
  System.out.println(s1 == s2);//false
  System.out.println(s1 == s3);//false
  System.out.println(s3 == s4);//true
}

Method of String

Compare strings

boolean equals(Object obj): compare whether the contents of strings are the same

boolean equalsIgnoreCase(String str): compare whether the contents of strings are the same, ignoring case

Method usage of String class

compareTo(String anotherString)
Compares two strings in dictionary order.

Code demonstration:

Requirements: simulate login, give three opportunities, and prompt several more times
Analysis:
A: Define two string objects to store the existing user name and password
B: Keyboard user name and password
C: Take the user name and password entered by the keyboard to compare with the existing user name and password
If the content is the same, you will be prompted to log in successfully
If the content is different, you will be prompted for login failure and several opportunities
public boolean equals(Object anObject): compare the contents of strings, strictly case sensitive (user name and password)
Public Boolean equals ignore case (string another string): compare the contents of a string, regardless of case (verification code)

public class StringTest {
	public static void main(String[] args) {
		//Define two string objects to store the existing user name and password
		String username = "admin";
		String password = "admin";
		
		for(int x=0; x<3; x++) {
			//Keyboard user name and password
			Scanner sc = new Scanner(System.in);
			System.out.println("Please enter the user name:");
			String name = sc.nextLine();
			System.out.println("Please input a password:");
			String pwd = sc.nextLine();
			
			//Take the user name and password entered by the keyboard to compare with the existing user name and password
			if(username.equals(name) && password.equals(pwd)) {
				System.out.println("Login successfully");
				break;
			}else {
				if((2-x) == 0){
					System.out.println("Your account is locked. Please contact the administrator");
				}else {
					System.out.println("Login failed, you still have"+(2-x)+"Second chance");
				}
			}
		}
	}

}

Acquisition function

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

public int length(): returns the number of characters in the string, the length of the string

Code demo

Requirement: traversal string (get every character in the string)

public class StringTest2 {
	public static void main(String[] args) {
		//To traverse a string, you first need to have a string
		String s = "abcde";
		
		//Thinking: how to get every character in a string
		//If let's provide a method, we should provide a method to return the characters in the specified position according to the index
		//Return value: char
		//Formal parameter: int index
		//public char charAt(int index): returns the value at the specified index
		//Primitive practice
		System.out.println(s.charAt(0));
		System.out.println(s.charAt(1));
		System.out.println(s.charAt(2));
		System.out.println(s.charAt(3));
		System.out.println(s.charAt(4));
		System.out.println("-------------------");
		
		//Improve with for loop
		for(int x=0; x<5; x++) {
			System.out.println(s.charAt(x));
		}
		System.out.println("-------------------");
		
		//At present, we count the data 5 in the for loop. Does the string provide a method to get the number of characters in the string?
		//public int length(): returns the number of characters in the string, the length of the string
		for(int x=0; x<s.length(); x++) {
			System.out.println(s.charAt(x));
		}
	}

}

String splicing

Requirement: splice the data in the array into a string according to the specified format
For example: int[] arr = {1,2,3};
Output: [1, 2, 3]

Analysis:
A: Define an array of type int
B: The implementation of write method splices the elements in the array into a string according to the specified format
C: Call method
D: Output results

public class StringTest3 {
	public static void main(String[] args) {
		//Define an array of type int
		int[] arr = {1,2,3};
		
		//The implementation of write method splices the elements in the array into a string according to the specified format
		
		//Calling method
		String result = arrayToString(arr);
		
		//Output result
		System.out.println("result:"+result);
	}
  /*
 * Two clear:
 * 		Return value type: String
 * 		Parameter list: int[] arr
 */
  public static String arrayToString(int[] arr) {
    String s = "";
    //[1, 2, 3]
    s+="[";

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

    s+="]";
    return s;
  }

}

Reversal

reverse() method

Requirements: String inversion
For example: keyboard input "abc"
Output: "cba"

Analysis:
A: Keyboard input string data
B: Write method to realize inversion of string data
Traverse the string backwards, and splice each character you get into a string
C: Call method
D: Output results

public class StringTest4 {
	public static void main(String[] args) {
		//Keyboard input string data
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a string:");
		String s = sc.nextLine();
		
		//Write method to realize inversion of string data
		
		//Calling method
		String result = reverse(s);
		
		//Output result
		System.out.println("result:"+result);
	}
	
	/*
	 * Two clear:
	 * 		Return value type: String
	 * 		Parameter list: String s
	 */
	public static String reverse(String s) {
		//Traverse the string backwards, and splice each character you get into a string
		String ss = "";
		
		for(int x=s.length()-1; x>=0; x--) {
			ss += s.charAt(x);
		}
		
		return ss;
	}

}

StringBuilder class

StringBuilder class overview

StringBuilder: is a variable string. String buffer class.

The difference between String and StringBuilder:

The content of String is fixed

The contents of StringBuilder are variable

+=Reason for memory consumption of concatenated strings:

Each concatenation will generate a new string object, and StringBuilder is used to concatenate strings, and the same StringBuilder container is used throughout

Common methods of StringBuilder class

A: Construction method:

​ public StringBuilder()

public StringBuilder(String str)

B: Member method:

public String toString(): returns the string representation of the data in this sequence.

Public StringBuilder append: adds data and returns the object itself.

public StringBuilder reverse(): reverse the string itself

StringBuilder: is a variable string class.

The difference between String and StringBuilder:
The content of String is fixed.
The contents of StringBuilder are variable.

Construction method
public StringBuilder()
public StringBuilder(String str)

public String toString(): returns the string representation of the data in this sequence.

public class StringBuilderDemo {
	public static void main(String[] args) {
		//public StringBuilder()
		StringBuilder sb = new StringBuilder();
		System.out.println("sb:"+sb);
		System.out.println(sb.length());
		System.out.println("----------------");
		
		//public StringBuilder(String str)
		StringBuilder sb2 = new StringBuilder("helloworld");
		System.out.println("sb2:"+sb2);
		System.out.println(sb2.length());
	}

}

Add function
Public StringBuilder append: adds data and returns the object itself.
Reversal function
public StringBuilder reverse()

public class StringBuilderDemo {
	public static void main(String[] args) {
		//create object
		StringBuilder sb = new StringBuilder();
		
		//Public StringBuilder append (any type)
		/*
		StringBuilder sb2 = sb.append("hello");
		
		System.out.println("sb:"+sb);
		System.out.println("sb2:"+sb2);
		System.out.println(sb == sb2);//true
		*/
		
		/*
		sb.append("hello");
		sb.append("world");
		sb.append(true);
		sb.append(100);
		*/
		
		//Chain programming
		sb.append("hello").append("world").append(true).append(100);
		
		System.out.println("sb:"+sb);
		
		//public StringBuilder reverse()
		sb.reverse();
		System.out.println("sb:"+sb);
	}

}

StringBuilder case

StringBuilder and String complete mutual conversion through methods

The mutual conversion of StringBuilder and String

StringBuilder – String
public String toString(): you can convert StringBuilder to String through toString()

String – StringBuilder
public StringBuilder(String s): you can convert a String to a StringBuilder through the construction method

public class StringBuilderTest {
	public static void main(String[] args) {
		/*
		//StringBuilder -- String
		StringBuilder sb = new StringBuilder();
		sb.append("hello");
		
		//FALSE
		//String s = sb;
		//public String toString()
		String s = sb.toString();
		System.out.println(s);
		*/
		
		//String -- StringBuilder
		String s = "hello";
		StringBuilder sb = new StringBuilder(s);
		System.out.println(sb);
	}

}

Using StringBuilder to splice arrays into a string

Give an example:

	int[] arr = {1,2,3};

Result:

	[1, 2, 3]

Concatenate an array into a string

For example: int[] arr = {1,2,3};
Output results: [1, 2, 3]

Analysis:
A: Define an array of type int
B: The implementation of write method splices the elements in the array into a string according to the specified format
C: Call method
D: Output results

public class StringBuilderTest2 {
	public static void main(String[] args) {
		//Define an array of type int
		int[] arr = {1,2,3};
		
		//The implementation of write method splices the elements in the array into a string according to the specified format
		
		//Calling method
		String result = *arrayToString*(arr);
		
		//Output result
		System.out.println("result:"+result);
	}
	
	/*
	 * Two clear:
	 * 		Return value type: String
	 * 		Parameter list: int[] arr
	 */
	public static String arrayToString(int[] arr) {
		StringBuilder sb = new StringBuilder();
		//[1, 2, 3]
		sb.append("[");
		
		for(int x=0; x<arr.length; x++) {
			if(x==arr.length-1) {
				sb.append(arr[x]);
			}else {
				sb.append(arr[x]).append(", ");
			}
		}
		
		sb.append("]");
		
		String s = sb.toString();
		
		return s;
		
	}

}

Using StringBuilder to complete string inversion

For example: keyboard input "abc"

Output: "cba"

Invert string
For example: keyboard input "abc"
Output: "cba"

Analysis:
A: Enter a string data by keyboard
B: Write method to realize inversion of string data
String – StringBuilder – reverse() – String
C: Call method
D: Output results

public class StringBuilderTest3 {
	public static void main(String[] args) {
		//Enter a string data by keyboard
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a string:");
		String s = sc.nextLine();
		
		//Write method to realize inversion of string data
		
		//Calling method
		String result = *myReverse*(s);
		
		//Output result
		System.out.println("result:"+result);
		
	}
	
	/*
	 * Two clear:
	 * 		Return value type: String
	 * 		Parameter list: String s
	 */
	public static String myReverse(String s) {
		//String -- StringBuilder -- reverse() -- String
		/*
		StringBuilder sb = new StringBuilder(s);
		sb.reverse();
		String ss = sb.toString();
		return ss;
		*/
		
		return new StringBuilder(s).reverse().toString();
	}

}
32 original articles published, 8 praised, 3403 visited
Private letter follow

Posted by akrocks_extreme on Tue, 04 Feb 2020 03:05:12 -0800