JAVA foundation - Common API I

Posted by bailo81 on Fri, 21 Jan 2022 23:07:32 +0100

Common API

1. Scanner class

1.1 what is the Scanner class

A simple text scanner that can parse basic types and strings. For example, the following code enables the user to download from system Read a number in:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Remarks: system In system input refers to entering data through the keyboard.

2. Anonymous object

concept
When creating an object, there are only statements to create the object, but the object address value is not assigned to a variable. Although it is a simplified way to create objects, the application scenarios are very limited.

  • Anonymous object: an object without a variable name

For example:

new Scanner(System.in).nextInt();

3. Random class

3.1 what is the Random class

Instances of this class are used to generate pseudo-random numbers
For example, the following code enables the user to get a random number:

Random r = new Random();
int i = r.nextInt();

3.2 Random construction method and member method

Construction method:

  • public Random(): create a new random number generator.

Member method:

  • public int nextInt(int n): returns a pseudo-random number with an int value between 0 (inclusive) and the specified value n (exclusive).

For example:
Obtain the random number between 1-n, including n

public class Test01Random {
    public static void main(String[] args) 
    {
        int n = 50;
        // create object
        Random r = new Random();
        // Get random number
        int number = r.nextInt(n) + 1;
        // Output random number
        System.out.println("number:" + number);
    }
}

4. ArrayList class

4.1 what is the ArrayList class

java.util.ArrayList is an implementation of a variable size array, and the data stored in it is called elements. This class provides methods to manipulate internally stored elements. Elements can be added continuously in ArrayList, and their size will grow automatically.

Represents a specified data type, called a generic type. E. Taken from the initial of Element. Where e appears, we can replace it with a reference data type, indicating which reference type elements we will store. For example:

ArrayList<String>,ArrayList<Student>

4.2 construction methods and common member methods

Construction method:

public ArrayList(): construct a collection with empty content.
Basic format:

ArrayList<String> list = new ArrayList<String>();

After JDK 7, the angle brackets of the right generic can be left blank, but < > still need to be written. Simplified format:

ArrayList<String> list = new ArrayList<>();

Common member methods:

  • Public Boolean add (E): adds the specified element to the tail of this collection.
  • public E remove(int index): removes the element at the specified position in this collection. Returns the deleted element.
  • public E get(int index): returns the element at the specified position in this collection. Returns the obtained element.
  • public int size(): returns the number of elements in this collection. When traversing a collection, you can control the index range to prevent out of bounds.

Parameter E, when constructing an ArrayList object, specifies what data type, so only objects of what data type can be added in the add (E, e) method.
Use the ArrayList class to store three string elements. The code is as follows:

public class Demo01ArrayListMethod
{
    public static void main(String[] args) 
    {
        //Create collection object
        ArrayList<String> list = new ArrayList<String>();
        //Add element
        list.add("hello");
        list.add("world");
        list.add("java");
        //public E get(int index): returns the element at the specified index
        System.out.println("get:"+list.get(0));
        System.out.println("get:"+list.get(1));
        System.out.println("get:"+list.get(2));
        //public int size(): returns the number of elements in the collection
        System.out.println("size:"+list.size());
        //public E remove(int index): deletes the element at the specified index and returns the deleted element
        System.out.println("remove:"+list.remove(0));
        //Traversal output
        for(int i = 0; i < list.size(); i++)
        {
        	System.out.println(list.get(i));
        }
    }
}

4.3 how to store basic data types

ArrayList objects cannot store basic types, but only data of reference types. Similar cannot be written, but the packaging type corresponding to the storage basic data type is OK. Therefore, to store basic type data, the data types in < > must be converted before writing. The conversion method is as follows:

Basic typeBasic type packing class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

5. String class

5.1 overview of string class

The class String includes methods for checking individual strings, such as comparing strings, searching strings, extracting substrings, and creating copies of strings with all characters translated to uppercase or lowercase.

characteristic:

  1. String unchanged: the value of the string cannot be changed after creation.
  2. Because String objects are immutable, they can be shared.

5.2 construction method

public String(): initializes the newly created String object to represent a null character sequence.
public String(char[] value): construct a new String through the character array in the current parameter.
public String(byte[] bytes): construct a new String by decoding the byte array in the current parameter using the platform's default character set. For example, the code is as follows:

// Nonparametric structure
String str = new String();

// Constructed from a character array
char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);

// Constructed by byte array
byte bytes[] = { 97, 98, 99 };
String str3 = new String(bytes);

5.3 common methods

Method of judging function

  • public boolean equals (Object anObject): compares this string with the specified object.
  • Public Boolean equalsignorecase (string otherstring): compares this string with the specified object, ignoring case.
    Method demonstration, the code is as follows:
public class String_Demo01 
{
    public static void main(String[] args) 
    {
    // Create string object
    String s1 = "hello";
    String s2 = "hello";
    String s3 = "HELLO";
    // boolean equals(Object obj): compare whether the contents of strings are the same
    System.out.println(s1.equals(s2)); // true
    System.out.println(s1.equals(s3)); // false
    System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
    //boolean equalsIgnoreCase(String str): compare whether the contents of strings are the same, ignoring case
    System.out.println(s1.equalsIgnoreCase(s2)); // true
    System.out.println(s1.equalsIgnoreCase(s3)); // true
    System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
    }
}

Note: Object means "Object" and is also a reference type. As a parameter type, it means that any Object can be passed to the method.

Method of obtaining function

  • public int length(): returns the length of this string.
  • public String concat (String str): connect the specified string to the end of the string.
  • public char charAt (int index): returns the char value at the specified index.
  • public int indexOf (String str): returns the index of the specified substring that appears in the string for the first time.
  • public String substring (int beginIndex): returns a substring, intercepting the string from beginIndex to the end of the string.
  • public String substring (int beginIndex, int endIndex): returns a substring and intercepts the string from beginIndex to endIndex. Including beginIndex and excluding endIndex.

example:

public class String_Demo02 
{
    public static void main(String[] args)
    {
        //Create string object
        String s = "helloworld";
        // int length(): gets the length of the string, which is actually the number of characters
        System.out.println(s.length());
        System.out.println("‐‐‐‐‐‐‐‐");
        
        // String concat (String str): concatenates the specified string to the end of the string
        String s = "helloworld";
        String s2 = s.concat("**hellojava");
        System.out.println(s2);//
        
        // char charAt(int index): gets the character at the specified index
        System.out.println(s.charAt(0));
        System.out.println(s.charAt(1));
        System.out.println("‐‐‐‐‐‐‐‐");
        
        // int indexOf(String str): get the index of the first occurrence of str in the string object, and return - 1
        System.out.println(s.indexOf("l"));
        System.out.println(s.indexOf("owo"));
        System.out.println(s.indexOf("ak"));
        
        System.out.println("‐‐‐‐‐‐‐‐");
        // String substring(int start): intercept the string from start to the end of the string
        System.out.println(s.substring(0));
        System.out.println(s.substring(5));
        System.out.println("‐‐‐‐‐‐‐‐");
        
        // String substring(int start,int end): intercepts a string from start to end. Including start, excluding end.
        System.out.println(s.substring(0, s.length()));
        System.out.println(s.substring(3,8));
    }
}

5.4 method of function conversion

  • public char[] toCharArray(): convert this string to a new character array.
  • public byte[] getBytes(): use the default character set of the platform to convert the String encoding into a new byte array.
  • public String replace (CharSequence target, CharSequence replacement): replace the string matching the target with the replacement string.

example:

public class String_Demo03 
{
    public static void main(String[] args) 
    {
        //Create string object
        String s = "abcde";
        //char[] toCharArray(): convert string to character array
        char[] chs = s.toCharArray();
        for(int x = 0; x < chs.length; x++) 
        {
        	System.out.println(chs[x]);
        }
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
        
        // byte[] getBytes(): convert string to byte array
        byte[] bytes = s.getBytes();
        for(int x = 0; x < bytes.length; x++) 
        {
        	System.out.println(bytes[x]);
        }
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
        
        //Replace the letter it with capital it
        String str = "itjava itJava";
        String replace = str.replace("it", "IT");
        System.out.println(replace); 
        System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
    }
}

CharSequence is an interface and a reference type. As a parameter type, you can pass a String object into a method.

5.5 method of dividing functions

  • public String[] split(String regex): splits this string into a string array according to the given regex (rule).

example:

public class String_Demo03 
{
    public static void main(String[] args)
    {
        //Create string object
        String s = "aa|bb|cc";
        String[] strArray = s.split("|"); // ["aa","bb","cc"]
        for(int x = 0; x < strArray.length; x++)
        {
        	System.out.println(strArray[x]); // aa bb cc
        }
	}
}

6. static keyword

6.1 static overview

About the use of static keyword, it can be used to modify member variables and member methods. The modified member belongs to a class, not just an object. In other words, since it belongs to a class, it can be called without creating an object.

6.2 definition and use format

Class variable
When static modifies a member variable, the variable is called a class variable. Each object of this class shares the value of the same class variable. Any object can change the value of the class variable, but you can also operate on the class variable without creating the object of the class.

  • **Class variable: * * member variable modified with static keyword.

Define format:

static Data type variable name;

give an example:

static int numberID

For example, when the new basic class starts, the students report for duty. Now I want to make a student number (SID) for each new student. Starting from the first student, sid is 1, and so on. The student number must be unique, continuous and consistent with the number of students in the class, so as to know what the student number to be assigned to the next new student is. In this way, we need a variable, which has nothing to do with each individual student object, but with the number of students in the whole class. Therefore, we can define a static variable numberOfStudent as follows:

public class Student 
{
    private String name;
    private int age;
    
    // Student id
    private int sid;
    
    // Class variable, record the number of students and assign student numbers
    public static int numberOfStudent = 0;
    
    public Student(String name, int age)
    {
        this.name = name;
        this.age = age;
        // Assign student numbers to students through numberOfStudent
        this.sid = ++numberOfStudent;
    }
    // Print attribute values
    public void show()
    {
    System.out.println("Student : name=" + name + ", age=" + age + ", sid=" + sid );
    }
}

public class StuDemo 
{
    public static void main(String[] args)
    {
        Student s1 = new Student("Zhang San", 23);
        Student s2 = new Student("Li Si", 24);
        Student s3 = new Student("Wang Wu", 25);
        Student s4 = new Student("Zhao Liu", 26);
        s1.show(); // Student: name = Zhang San, age=23, sid=1
        s2.show(); // Student: name = Li Si, age=24, sid=2
        s3.show(); // Student: name = Wang Wu, age=25, sid=3
        s4.show(); // Student: name = Zhao Liu, age=26, sid=4
    }
}

Static method

When static modifies a member method, the method is called a class method. Static methods have static in the declaration. It is recommended to call them with the class name instead of creating the object of the class. The call method is very simple.

  • **Class method: * * member method modified with static keyword, which is customarily called static method.

Define format:

Modifier  static Return value type method name (parameter list)
{
	// Execute statement
}

Example: define static methods in Student class

public static void showNum() 
{
	System.out.println("num:" + numberOfStudent);
}
  • Precautions for static method invocation:
    • Static methods can directly access class variables and static methods.
    • Static methods cannot directly access ordinary member variables or member methods. Conversely, member methods can directly access class variables or static methods.
    • this keyword cannot be used in static methods.

Tip: static methods can only access static members.

Call format

Members modified by static can and are recommended to be accessed directly through the class name. Although static members can also be accessed through object names, because multiple objects belong to the same class and share the same static member, it is not recommended and a warning message will appear.

Format:

// Access class variables
 Class name.Class variable name;

// Call static method
 Class name.Static method name(parameter);

6.3 static principle diagram

static modification:

  • It is loaded as the class is loaded, and it is loaded only once.
  • It is stored in a fixed memory area (static area), so it can be called directly by the class name.
  • It takes precedence over objects, so it can be shared by all objects.

6.4 static code block

  • Static code block: a code block {} defined at the member position and decorated with static.
    • Location: outside the method in the class.
    • Execution: it is executed once as the class is loaded, which takes precedence over the execution of main method and constructor method.

Format:

public class ClassName
{
    static {
   	 // Execute statement
    }
}

Function: initialize and assign values to class variables. Usage demonstration, the code is as follows:

public class Game 
{
    public static int number;
    public static ArrayList<String> list;
    static 
    {
        // Assign values to class variables
        number = 2;
        list = new ArrayList<String>();
        // Add element to collection
        list.add("Zhang San");
        list.add("Li Si");
    }
}

Tip: static keyword can modify variables, methods and code blocks. In the process of using, the main purpose is to call methods without creating objects.

7. Arrays class

7.1 what are Arrays

java. util. The arrays class contains various methods for manipulating arrays, such as sorting and searching. All its methods are static methods, which are very simple to call.

7.2 methods of manipulating arrays

  • public static String toString(int[] a): returns the string representation of the specified array content.
public static void main(String[] args)
{
    // Define int array
    int[] arr = {2,34,35,4,657,8,69,9};
    // Print the array and output the address value
    System.out.println(arr); // [I@2ac1fdc4
    // Convert array contents to strings
    String s = Arrays.toString(arr);
    // Print string, output content
    System.out.println(s); // [2, 34, 35, 4, 657, 8, 69, 9]
}
  • public static void sort(int[] a): sort the specified int array in ascending numerical order.
public static void main(String[] args) 
{
    // Define int array
    int[] arr = {24, 7, 5, 48, 4, 46, 35, 11, 6, 2};
    System.out.println("Before sorting:"+ Arrays.toString(arr)); // Before sorting: [24, 7, 5, 48, 4, 46, 35, 11, 6, 2]
        
    // Ascending sort
    Arrays.sort(arr);
    System.out.println("After sorting:"+ Arrays.toString(arr));// After sorting: [2, 4, 5, 6, 7, 11, 24, 35, 46, 48]
}

7.3 practice

Please use the API s related to Arrays to arrange all characters in a random string in ascending order and print them in reverse order.

public class ArraysTest 
{
    public static void main(String[] args) 
    {
        // Define random strings
        String line = "ysKUreaytWTRHsgFdSAoidq";
        // Convert to character array
        char[] chars = line.toCharArray();
        // Ascending sort
        Arrays.sort(chars);
        // Reverse traverse printing
        for (int i = chars.length‐1; i >= 0 ; i‐‐) 
        {
            System.out.print(chars[i]+" "); // y y t s s r q o i g e d d a W U T S R K H F A
        }
	}
}

8. Math class

8.1 what is the Math class

java. The lang. math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions. For a tool class like this, all its methods are static methods and will not create objects. It is very simple to call.

8.2 basic operation method

  • public static double abs(double a): returns the absolute value of the double value.
double d1 = Math.abs(‐5); //The value of d1 is 5
double d2 = Math.abs(5); //The value of d2 is 5
  • public static double ceil(double a): returns the smallest integer greater than or equal to the parameter.
double d1 = Math.ceil(3.3); //The value of d1 is 4.0
double d2 = Math.ceil(‐3.3); //The value of d2 is ‐ 3.0
double d3 = Math.ceil(5.1); //The value of d3 is 6.0
  • public static double floor(double a): returns an integer less than or equal to the maximum parameter.
double d1 = Math.floor(3.3); //The value of d1 is 3.0
double d2 = Math.floor(‐3.3); //The value of d2 is ‐ 4.0
double d3 = Math.floor(5.1); //The value of d3 is 5.0
  • public static long round(double a): returns the long closest to the parameter. (equivalent to rounding method)
long d1 = Math.round(5.5); //The value of d1 is 6.0
long d2 = Math.round(5.4); //The value of d2 is 5.0

8.3 practice

Please use Math related API s to calculate the number of integers with absolute values greater than 6 or less than 2.1 between - 10.8 and 5.9?

public class MathTest 
{
    public static void main(String[] args) 
    {
        // Define minimum value
        double min = ‐10.8;
        // Define maximum
        double max = 5.9;
        // Define variable count
        int count = 0;
        // Cycle in range
        for (double i = Math.ceil(min); i <= max; i++) 
        {
            // Get absolute value and judge
            if (Math.abs(i) > 6 || Math.abs(i) < 2.1)
                {
                // count
                count++;
            }
        }
        System.out.println("The number is: " + count + " individual");
    }
}

Topics: Java api JavaSE