Java advanced development

Java advanced development

1.API overview

1.1. Knowledge overview

API(Application Programming Interface). The Java API is a query manual for developers and a description document for our classes in the JDK. These classes encapsulate the underlying code. We don't need to care about how these classes are implemented, we just need to learn how to use these classes. Therefore, we can learn the classes provided in the Java class library and know how to use them by querying the API manual.

1.2. Use steps of API manual

1. Open the help document.

2. Click display, click index, find and type the input box.

3. Which class or interface are you looking for? Enter in the input box and press enter.

4. Look at the bag.

5. See the explanation and description of the class.

6. Learn the construction method.

7. Use member variables and member methods.

1.3. Classroom questioning

1. What is the latest version of JDK?

2. Why do API manuals 1.8 and 1.6 use JDK1.8 but still use 1.6API manual?

Because the JDK1.6 Chinese manual is the simplified Chinese manual officially translated by SUN, while the JDK1.8 manual is the translation of other translation software, which is not very standard.

1.4.JDK package structure

packagefunction
java.langThe basic classes of Java programs, such as string, multithreading, etc. the classes in this package are used very frequently, so the classes under this package do not need to guide the package during use.
java.utilCommon tool classes, such as Scanner, collection, random number generator, calendar and clock.
java.ioJava operation class for system files, read and write operations.
java.netNetwork operations in Java.
java.mathMathematical operations in Java.
java.securitySecurity related operations in Java.
java.textDeal with text, date, digital information and other formats in Java.

1.5. Document notes


2.Scanner class

2.1. Knowledge overview

A simple text scanner that can parse basic data types and strings.

2.2. Usage steps of reference data type

1. Guide Package

Use the import keyword to import packages and introduce the types to be used. Note that classes under the java.lang package do not need to import packages.

Format:

import Package name.Class name;

give an example:

import java.util.Scanner;

2. Create object

Use the class's construction method to create the class's objects.

Format:

Data type object name=new data type();

give an example:

Scanner scan=new Scanner(System.in);

3. Use attributes or methods

Use the member method of this class to complete the specified function.

Format:

Object name.Method name();

give an example:

int i=sacn.nextInt();//An integer of type Int that receives keyboard input.

Use Scanner to complete the code entered by keyboard:

package cn.tedu.Scanner;
import java.util.Scanner;
/**
 * 1, Knowledge overview:
 *  A simple text scanner that can parse basic data types and strings.
 * 2, To use a reference data type
 * 1.Guide Package
 *  Use the import keyword to import packages and introduce the types to be used. Note that classes under the java.lang package do not need to import packages.
 *  Format: import package name. Class name;
 * 2.create object
 *  Data type object name = new data type ();
 * 3.Use properties or methods
 *  Object name. Method name ();
 *  
 * @author Administrator
 *
 */
public class ScannerDemo1 {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("please enter a number:");
		int num=scan.nextInt();
		System.out.println("The scanned number is:"+num);
		//Turn off the scanner
		scan.close();
	}

}
package cn.tedu.Scanner;
import java.util.Scanner;
/**
 * 1, Knowledge overview:
 *  A simple text scanner that can parse basic data types and strings.
 * 2, To use a reference data type
 * 1.Guide Package
 *  Use the import keyword to import packages and introduce the types to be used. Note that classes under the java.lang package do not need to import packages.
 *  Format: import package name. Class name;
 * 2.create object
 *  Data type object name = new data type ();
 * 3.Use properties or methods
 *  Object name. Method name ();
 * @author Administrator
 *
 */
public class ScannerDemo2 {

	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("Please enter text:");
		String num=scan.nextLine();
		System.out.println("The scanned text is:"+num);
		//Turn off the scanner
		scan.close();
	}
}

2.3. Key points of interview

What is the difference between the next() method and the nextLine() method?

Both the next() and nextLine() methods in the Scanner can scan the console string. The difference is that the next() method starts scanning when it meets the first valid character (non space or newline character), and ends scanning when it meets the first separator or terminator. The nextLine() method obtains a line of content and returns it as a string. It ends when a newline character is encountered.

3.Random class

3.1. Knowledge overview

This class mainly generates random numbers.

3.2. Usage steps of random class

1. View class (Guide Package)

java.util.Random: this class requires import package

2. View construction method (create object)

public Random(): create a new random number generator

3. View members (using member methods or variables)

  • public int nextInt(): returns a random number with a random range of - 2147483648 to 2147483647, evenly distributed.
  • public int nextInt(int n): returns a random number, which is evenly distributed from 0 (inclusive) to n (exclusive).
  • public long nextLong(): returns a random number with a random range of long, which is evenly distributed among the value ranges.
  • public double nextDouble(): returns a random number. The random range is double. The value ranges are evenly distributed.
  • public boolean nextBoolean(): returns a random number with a random range of boolean uniform distribution (true, false).

3.3. Classroom exercises

Random is used to generate 3 random numbers, ranging from 0 to 50.

package cn.tedu.Random;
//1. Guide Package
import java.util.Random;
/**
 * Classroom exercises:
 * Generate 3 random numbers, ranging from 0 to 50.
 * @author Administrator
 */
public class RandomDemo2 {

	public static void main(String[] args) {
		//2. Create object
		Random ran=new Random();
		//3. Generate random numbers using loops
		for(int i=0;i<3;i++){
			int num=ran.nextInt(50);
			System.out.println(num);
		}
	}
}

3.4. Homework after class

Use Random to generate three Random numbers, print all of them to the console, and take out the maximum of the three Random numbers.

package cn.tedu.API;

/**
 * Use Random to generate three Random numbers, print all of them to the console, and take out the maximum of the three Random numbers.
 */

import java.util.Random;

public class HomeWork {
    public static void main(String[] args) {
        Random random = new Random();
        int a=random.nextInt(100);
        int b=random.nextInt(100);
        int c=random.nextInt(100);
        System.out.println("Random number one:"+a+"Random number two:"+b+"Random number three:"+c);
        int temp=a>b?a:b;
        int max=temp>c?temp:c;
        System.out.println("The maximum value is:"+max);
    }
}

4.Math class

4.1. Knowledge overview

The java.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 divided into static methods, and objects will not be created. It is very simple to call.

4.2. Basic operation method

public static int abs(int a):return int type a Absolute value of.
  //Returns the absolute value of int type a.
   int abs1 = Math.abs(5);
   System.out.println(abs1);//5
   int abs2 = Math.abs(-5);
   System.out.println(abs2);//5
public static double ceil(double a):Return parameters greater than or equal to a The smallest integer of.
   //Returns the smallest integer greater than or equal to parameter a.
    double ceil1 = Math.ceil(4.1);
    System.out.println(ceil1);//5.0
    double ceil2 = Math.ceil(-3.3);
    System.out.println(ceil2);//-3.0
public static double floor(double a):Returns the maximum integer less than or equal to the parameter.
   //Returns the maximum integer less than or equal to the parameter.
   double floor1 = Math.floor(3.3);
   System.out.println(floor1);//3.0
   double floor2 = Math.floor(-3.3);
   System.out.println(floor2);//-4.0
public static long round(double a):Returns the closest parameter a of long Value.(Similar to rounding)
    //Returns the long value closest to parameter a. (similar to rounding)
    long round1 = Math.round(5.5);
    System.out.println(round1);
    long round2 = Math.round(-5.5);
    System.out.println(round2);
public static double random():Return 0(include)To 1(barring)Random decimals between.
//Returns a random decimal from 0 (inclusive) to 1 (exclusive).
double random = Math.random();
System.out.println(random);

Full code:

package cn.tedu.Math;
/**
 * Math Class overview:
 * java.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 divided into static methods, and objects will not be created. It is very simple to call.
 * Math Basic operation method of class:
 * public static int abs(int a):Returns the absolute value of int type a.
 * public static double ceil(double a):Returns the smallest integer greater than or equal to parameter a.
 * public static double floor(double a):Returns the maximum integer less than or equal to the parameter.
 * public static long round(double a):Returns the long value closest to parameter a. (similar to rounding)
 * public static double random():Returns a random decimal from 0 (inclusive) to 1 (exclusive).
 * @author MaYF
 *
 */
public class MathDemo1 {

	public static void main(String[] args) {
		// Returns the absolute value of int type a.
		int abs1 = Math.abs(5);
		System.out.println(abs1);// 5
		int abs2 = Math.abs(-5);
		System.out.println(abs2);// 5
		System.out.println("---------------");
		// Returns the smallest integer greater than or equal to parameter a.
		double ceil1 = Math.ceil(4.1);
		System.out.println(ceil1);// 5.0
		double ceil2 = Math.ceil(-3.3);
		System.out.println(ceil2);// -3.0
		System.out.println("---------------");
		// Returns the maximum integer less than or equal to the parameter.
		double floor1 = Math.floor(3.3);
		System.out.println(floor1);// 3.0
		double floor2 = Math.floor(-3.3);
		System.out.println(floor2);// -4.0
		System.out.println("---------------");
		// Returns the long value closest to parameter a. (similar to rounding)
		long round1 = Math.round(5.5);
		System.out.println(round1);
		long round2 = Math.round(-5.5);
		System.out.println(round2);
		System.out.println("---------------");
		// Returns a random decimal from 0 (inclusive) to 1 (exclusive).
		double random = Math.random();
		System.out.println(random);
	}
}

4.3. Classroom exercises

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

package cn.tedu.homework;
/**
 * 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?
 * @author MaYF
 */
public class ABSCount {

	public static void main(String[] args) {
		// Define minimum
		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");
		}
}

5.String class

5.1. Knowledge overview

The java.lang.String class represents a string. All string literals (such as "abc") in Java programs can be regarded as examples of implementing this class.

The String class includes methods for detecting individual strings. For example, it is used to compare strings, search strings, extract substrings, and create copies of strings with all characters converted to uppercase or lowercase.

5.2. String characteristics

1. The string is unchanged: the value of the string cannot be changed after creation (final decoration).

package cn.tedu.String;
/**
 * String class
 * characteristic:
 * 1.String Immutable
 * @author Administrator
 *
 */
public class StringDemo1 {

	public static void main(String[] args) {
		String s="abc";
		System.out.println(s);
		String s1=s+"d";
		//s+="d";
		System.out.println(s);
		System.out.println(s1);

	}
}

2. String sharing: because string objects are immutable, they can be shared.

3. Underlying storage: "abc" is equivalent to char[] data = {a ',' b ',' c '}; Character array - string

Char array is used to store the String, and the underlying byte [] byte array of char.

5.3. Use steps

1. View class

java.lang.String: this class does not need to import packages.

2. View construction method

public String(): create a new String object with a null character sequence.

public String(char[] value): create a new string object through the character array value in the current parameter.

public String(byte[] bytes): creates a string object by using the bytes in the decoding parameters of the platform's default character set.

package cn.tedu.String;
/**
 * String Class is created using construction methods
 * public String(): Create a new String object with a null character sequence.
 * 
 * public String(char[] value):
 * Create a new string object from the character array value in the current parameter.
 * 
 * public String(byte[] bytes):
 * Create a string object by decoding the bytes in the parameters using the platform's default character set.
 * @author Administrator
 *
 */
public class StringDemo2 {

	public static void main(String[] args) {
		//Mode 1:
		String str1=new String();
		System.out.println(str1);
		//Mode 2:
		char[] ch={'a','b','c'};
		String str2=new String(ch);
		System.out.println(str2);
		//Mode 3:
		byte[] by={97,98,99};
		String str3=new String(by);
		System.out.println(str3);
		//Mode 4:
		String str4="abc";
		System.out.println(str4);
	}
}

5.4. Common methods

public boolean equals(Object anObject): compares the current string with the specified string anObject to see whether it is equal.

Public Boolean equalsignorecase (string otherstring): compare the current string with the specified string anObject to see if they are equal, ignoring case.

public boolean startsWith(String prefix): tests whether the current string starts with the specified prefix.

public boolean endsWith(String suffix): tests whether the current string ends with the specified suffix.

package cn.tedu.String;
/**
 * String Common methods of class:
 * public boolean equals(Object anObject): Compares the current string with the specified string anObject for equality.
 * 
 * public boolean equalsIgnoreCase(String anotherString): Compares the current string with the specified string anObject for equality, ignoring case.
 * 
 * public boolean startsWith(String prefix):Tests whether the current string starts with the specified prefix.
 * 
 * public boolean endsWith(String suffix):Tests whether the current string ends with the specified suffix.
 * @author Administrator
 */
public class StringDemo3 {

	public static void main(String[] args) {
		//Create string object
		String s1="hello";
		String s2="hello";
		String s3="HELLO";
		char[] ch={'h','e','l','l','o'};
		String s4=new String(ch);
		String s5=null;
		System.out.println(s1.equals(s2));//true
		System.out.println(s1.equals(s3));//false
		System.out.println(s1.equals(s4));//true
		System.out.println(s1.equals(s5));//false
        //Any empty object cannot call properties and methods, otherwise the following exceptions will be reported
        //java.lang.NullPointerException null pointer exception, which should be avoided.
		//System.out.println(s5.equals(s1));
		System.out.println("------------------");
		System.out.println(s1.equalsIgnoreCase(s2));//true
		System.out.println(s1.equalsIgnoreCase(s3));//true
		System.out.println("------------------");
		String str="Thinking in Java";
		System.out.println(str.startsWith("T"));//true
		System.out.println(str.endsWith("Java"));//true
		System.out.println(str.startsWith("thinking"));//false	
	}
}

5.5. Method of obtaining function

public int length(): returns the length of this string.

public String concat(String str): connects the specified string str to the end of the current string.

public char charAt(int index): returns the char character at the specified index in the current string.

public int indexOf(String str): returns the index of the specified string str at the index position of the current string for the first time. If not, it returns - 1.

public String substring(int beginIndex): returns a substring, which is intercepted from the beginIdex subscript position of the current string to the end of the current string.

public String substring(int beginIndex,int endIndex): returns a substring, intercepted from the beginIndex subscript position of the current string to the endIndex subscript position of the current string, including beginIndex and excluding endIndex.

package cn.tedu.String;
/**
 * How to get the function:
 * public int length():
 * Returns the length of this string.
 * public String concat(String str):
 * Connects the specified string str to the end of the current string.
 * public char charAt(int index):
 * Returns the char character at the specified index in the current string.
 * public int indexOf(String str):
 * Returns the first occurrence of the specified string str
 * The index position index of the current string. If there is no index, return - 1.
 * public String substring(int beginIndex):
 * Returns a substring from the beginIdex of the current string
 * The subscript position begins to intercept to the end of the current string.
 * public String substring(int beginIndex,int endIndex):
 * Returns a substring starting from the beginIndex subscript position of the current string
 * Intercept to the end of the endIndex subscript position of the current string,
 * Contains beginIndex, not endIndex.
 * 
 * @author Administrator
 *
 */
public class StringDemo5 {

	public static void main(String[] args) {
		//Create string object
		String s="helloworld";
		int length=s.length();
		System.out.println("The length of the string is:"+length);//String length: 10
		System.out.println("------------------");
		String s1=s.concat("**hello tedu");
		System.out.println(s1);//helloworld**hello tedu
		System.out.println("------------------");
		System.out.println(s.charAt(0));//h
		System.out.println(s.charAt(9));//d
		System.out.println("------------------");
		System.out.println(s.indexOf("l"));//2
		System.out.println(s.indexOf("owo"));//4
		System.out.println(s.indexOf("ak"));//-1
		System.out.println("------------------");
		System.out.println(s.substring(1));//elloworld
		System.out.println(s.substring(5));//world
		System.out.println("------------------");
		System.out.println(s.substring(4, 7));//owo
		System.out.println(s.substring(5,s.length()));//world		
	}
}

5.6. Classroom exercises

Define a method to take out the int array {1,2,3} and splice it into a string according to the specified format.

Format: [word1#word2#word3]

Result: [1#2#3]

package cn.tedu.String;
/**
 * Classroom exercises:
 *  Define a method to get the int array {1,2,3} according to the specified format
 *  Spliced into a string. Format: [word1#word2#word3]
 *  [1#2#3]
 * @author Administrator
 *
 */
public class StringDemo6 {

	public static void main(String[] args) {
		//Create int array
		int[] arr={1,2,3};
		//Call splicing method
		String s=arrayToString(arr);
		System.out.println("The spliced string is:"+s);
	}
	/**
	 * String splicing method
	 * @param arr Array to be spliced
	 * @return Spliced string
	 */
	public static String arrayToString(int[] arr){
		String s="[";
		//Traversal array
		for(int i=0;i<arr.length;i++){
			if(i==arr.length-1){
			//To the last element of the array,
			//Splice the current element and on the original basis]
				s=s.concat(arr[i]+"]");//[1#2#3]
			}else{
		//As long as there is no last array element,
		//Splice the current array elements and on the original basis#
				s=s.concat(arr[i]+"#");//[1#2#
			}
		}
		return s;
	}
}

5.7. Method of function conversion

public char[] toCharArray(): converts the current string into a character array.

public byte[] getBytes(): converts the current string into a new byte array using the platform default character set encoding.

public String replace(CharSequence target, CharSequence replacement): replace the string matching the target with the replacement string.

package cn.tedu.String;
/**
 * Method of converting functions:
 * public char[] toCharArray():Converts the current string to a character array.
 * public byte[] getBytes():Converts the current string into a new byte array using the platform default character set encoding.
 * public String replace(CharSequence target, CharSequence replacement):Replace the string matching the target with the replacement string.
 * 
 * 
 * @author Administrator
 *
 */
public class StringDemo7 {

	public static void main(String[] args) {
		//Create string object
		String s="abcde";
		//Converts a string to a character array
		char[] chs=s.toCharArray();
		//Traversal array
		for (int i = 0; i < chs.length; i++) {
			System.out.println(chs[i]);
		}
		System.out.println("------------------");
		//Convert string to byte array
		byte[] bytes=s.getBytes();
		//Traversal array
		for (int i = 0; i < bytes.length; i++) {
			System.out.println(bytes[i]);
		}
		System.out.println("------------------");
		String str="ittarena ittedu";
		String str1=str.replace("it", "IT");
		System.out.println(str1);
	}
}

Tip: CharSequence is an interface and a reference type. As a parameter type, you can pass a String object into a method. Replace all existing original strings with new strings, and return the new String after replacement.

5.8. Homework after class

Count the number of characters

Enter a character on the keyboard to count the number of uppercase letters, lowercase letters and numeric characters in the string.

Tags: Java

Posted on Thu, 16 Sep 2021 15:30:53 -0400 by friedice