Common classes in Java

Posted by Sindarin on Sun, 02 Jan 2022 22:34:10 +0100

1, Basic data type wrapper class

java is a pure object-oriented language, but there are eight basic data types in java, which destroys the pure object-oriented characteristics of java. In order to promise that everything is an object in java, java matches each basic data type with a class, which we call wrapper class / encapsulation class.

Note: each basic data type has a wrapper class that matches it.

1.1 packaging of eight basic data types

byte Byte extends Number extends Object
short Short extends Number extends Object
int Integer extends Number extends Object
long Long extends Number extends Object
float Float extends Number extends Object
double Double extends Number extends Object
char Character extends Object
boolean Boolean extends Object

be careful:

  1. Numeric types inherit Number
  2. The wrapper class of int is written as Integer
  3. The packing class of Character is written as: Character
  4. The wrapper classes of other basic data types are capitalized by the first letter of the basic type.

1.2 common methods in packaging

Packing: basic data type -- > Packing class

Integer i1 = new Integer(10); // Using construction method

Integer i2 = Integer.valueOf(10); // Using static methods in wrapper classes

int i = 100;
Integer integer1 = Integer.valueOf(i);//Packing using static methods in wrapper classes
Integer integer2 = new Integer(100);//Packing by construction method
System.out.println(integer1);  //100
System.out.println(integer2);  //100

Unpacking: packing class -- > basic data type

Integer integer = new Integer(100);
int i = integer.intValue();//Unpacking
System.out.println(i);

From jdk1 Since 5, java has added automatic packing and unpacking operations for basic data types.

Automatic packing: a basic data type can be directly assigned to the packing class

int i = 100;
Integer integer = i;//Automatic boxing (bottom implementation: Integer.valueOf(i);)
System.out.println(integer);

Automatic unpacking: you can directly assign a packing class object to the basic data type

Integer integer = new Integer(100);
int i = integer;//Automatic unpacking (bottom layer implementation: integer.intValue();)
System.out.println(i);

Automatic packing and unpacking simplify the operation of packaging.

Application scenario: a collection (similar to an array container), but the collection can only store reference data types. If you want to store basic data types, you can convert the basic data types to corresponding wrapper objects

give an example:

Requirement: convert string array {"1", "2", "3", "4", "5", "6"} into int array

package com.dream.package_class;

public class Test02 {
	
	public static void main(String[] args) {

		String[] ss = {"1","2","3","4","5"};
		
		int[] is = new int[ss.length];
		
		for (int i = 0; i < is.length; i++) {
			//1. Convert String to Integer object
			//2.Integer objects are automatically unpacked into int data
			int num = Integer.valueOf(ss[i]);
			
			is[i] = num;
		}
		
		for (int element : is) {
			System.out.println(element);
		}
	}
}
/*
	Output results:
		1
        2
        3
        4
        5
*/

1.3 deep into the underlying source code of packaging

Interview questions:

Integer integer1 = Integer.valueOf(100);
Integer integer2 = Integer.valueOf(100);
System.out.println(integer1 == integer2);//true

Integer integer3 = Integer.valueOf(200);
Integer integer4 = Integer.valueOf(200);
System.out.println(integer3 == integer4);//false

There is a cache class at the bottom of Integer. There is an array in the cache class, which stores Integer objects of - 128 ~ 127 Valueof (Num) the bottom layer will judge whether num is in the range of - 128 ~ 127. If it is included, it will get data from the cache array. If it is not in this range, it will create a new object

Write a similar underlying source code yourself

package com.dream.package_class;

public class MyInteger {
	
	private int value;

	public MyInteger(int value) {
		this.value = value;
	}
	
	public static MyInteger valueOf(int i){
		if(i >= MyIntegerCache.low && i <= MyIntegerCache.high){
			return MyIntegerCache.cache[i - MyIntegerCache.low];
		}
		return new MyInteger(i);
	}
	
	//Buffer class for MyInteger
	private static class MyIntegerCache{
		
		private static final int low = -128;
		private static final int high = 127;
		private static final MyInteger[] cache; 
		
		static{
			//Initialize buffer array
			cache = new MyInteger[high - low + 1];
			int j = low;
			for (int i = 0; i < cache.length; i++) {
				cache[i] = new MyInteger(j++);
			}
		}
	}
	@Override
	public String toString() {
		return Integer.toString(value);
	}
}

2, String related classes

1. String class

1.1 what is a String

1. String is an immutable class, that is, once a string object is created, the character sequence contained in the object cannot be changed until the object is destroyed.

2. String class is final and cannot have subclasses.

1.2 creating string objects

Constant pool concept:

The Java runtime will maintain a constant pool, which is used to store various strings generated in the runtime, and the contents of strings in the pool are not repeated.

Some problems about creating objects with String

package com.dream.string_class;

public class Test05 {
	
	public static void main(String[] args) {
		/**
		 * Knowledge points: go deep into the problem of creating String objects
		 */
		
		String str1 = "abc";
		String str2 = "abc";
        //At this time, it is equal because the string "abc" in the constant pool will be used directly from the constant pool when defining str2. The address is the same, so the following statement returns true
		System.out.println(str1 == str2);//true
		
		//Two constant strings are spliced directly at compile time
        //After the same splicing, "abc" is still the string assignment from the constant pool
		String str3 = "ab" + "c";
		System.out.println(str3 == str1);//true
		
		//Two constant strings are spliced directly at compile time
		final String s1 = "ab";
		final String s2 = "c";
		String str4 = s1+s2;//Same as above
		System.out.println(str4 == str1);//true
		
		//The bottom layer of string splicing of two variables is to create a StringBuilder object
		String s3 = "ab";
		String s4 = "c";
		String str5 = s3+s4;//new StringBuilder(s3).append(s4).toString()
		System.out.println(str5 == str1);//false
	}
}

1.3 common methods of string class

package com.dream.string_class;

public class Test01 {
	
	public static void main(String[] args) {
		
		String str = "123abc";
		
		str = str.concat("DEF123");//Append a string to the end of this string and return a new string
		str = str.substring(2);//Truncate from the beginning subscript to the end of the string and return a new string
		str = str.substring(1, 7);//Intercept from the start subscript (inclusive) to the end subscript (exclusive), and return a new string
		str = str.toUpperCase();//Convert to uppercase and return a new string
		str = str.toLowerCase();//Convert to lowercase and return a new string
		
		str = "   123 a  bcD EF 123        ";
		
		str = str.trim();//Removes leading and trailing spaces and returns a new string
		str = str.replace('2', '-');//Replace characters and return a new string
		str = str.replaceFirst("3", "XXX");//Replaces the first occurrence of the string and returns a new string
		str = str.replaceAll("1", "xxx");//Replace the string and return a new string
		str = str.replaceAll(" ", "");//Replace the string and return a new string
		
		System.out.println("Judge whether the contents of two strings are the same:(Case sensitive)" + str.equals("xxx-XXXabcDEFxxx-3"));
		System.out.println("Judge whether the contents of two strings are the same:(Case insensitive)" + str.equalsIgnoreCase("XXX-XXXABCdefxxx-3"));
		System.out.println("Determine whether this string starts with a string:" + str.startsWith("xxx"));
		System.out.println("Determine whether this string ends with a string:" + str.endsWith("-3"));
		
		System.out.println("Query the subscript of this string in the target string for the first time:" + str.indexOf("-"));
		System.out.println("Query the last subscript of this string in the target string:" + str.lastIndexOf("-"));
		
		System.out.println("Gets the character on the specified subscript:" + str.charAt(4));
		
		//xxx-XXXabcDEFxxx-3	
		System.out.println(str);	
	}
}
package com.dream.string_class;

public class Test02 {
	
	public static void main(String[] args) {
		
		//Convert other types to strings
		
		int i = 100;
		System.out.println(String.valueOf(i));
		
		boolean bool = true;
		System.out.println(String.valueOf(bool));		
	}
}

Exercise: complete a mailbox format check hhy@qq.com

(1) "@" cannot be in the first place
(2),“.” Can't be last
(3) "@" and "." There should be characters in the middle
(4),***@***.***

package com.dream.string_class;

public class Test03 {
	
	public static void main(String[] args) {
		
		String email = "hhy@qq.com";
		
		int index1 = email.indexOf("@");//Get subscript
		int index2 = email.indexOf(".");//Get subscript
		
		if(index1 == 0 || index2 == email.length()-1 || (index2-index1)<=1){
			System.out.println("Mailbox format error");
		}	
	}
}

Interview questions

Interview question 1: the following code creates several String objects (test point: the value in the constant pool must be unique)

String str1 = "abc";
String str2 = "abc";
//The answer is one

Interview question 2: the following code creates several String objects (test point: the value in the constant pool must be unique)

String str1 = new String("abc");
String str2 = new String("abc");
//Answer: Three

2. StringBuffer class

1. StringBuffer represents a variable character sequence.

2. StringBuffer is called string buffer

3. Its working principle is to apply for a piece of memory in advance to store the character sequence. If the character sequence is full, the size of the cache will be changed again to accommodate more character sequences.

4. String Buffer is a variable object, which is the biggest difference between strings

5. Inheritance relationship: StringBuffer extends AbstractStringBuilder

6. Default string buffer: 16 characters

package com.dream.stringbuffer_class;

public class Test01 {
	
	public static void main(String[] args) {

		//StringBuffer sb = new StringBuffer();
		
		//Custom string buffer: 100 characters
		//StringBuffer sb = new StringBuffer(100);
	
		//Custom string buffer: "123abc" Length () + 16: 22 characters
		StringBuffer sb = new StringBuffer("123abc");
	
		sb.append("DEF123");//Append string at the end
		sb.insert(6, "xxx");//Inserts a string at the specified subscript
		sb.setCharAt(3, 'A');//Replaces the character on the specified subscript
		sb.replace(6, 9, "aaaa");//A string that is replaced from the start subscript (inclusive) to the end subscript (exclusive)
		
		sb.deleteCharAt(1);//Deletes the character on the specified subscript
		sb.delete(5, 11);//Delete the string from the start subscript (inclusive) to the end subscript (exclusive)
		sb.reverse();//Reverse string
		//321FcbA31
		System.out.println(sb);	
	}
}

3. StringBuilder

StringBuilder and StringBuffer are as like as two peas, because two classes inherit AbstractStringBuilder and the methods inside are all called methods of the parent class.

package com.dream.stringbuilder_class;

public class Test01 {
	
	public static void main(String[] args) {
		//Default string buffer: 16 characters
		//StringBuilder sb = new StringBuilder();
		
		//Custom string buffer: 100 characters
		//StringBuilder sb = new StringBuilder(100);
	
		//Custom string buffer: "123abc" Length () + 16: 22 characters
		StringBuilder sb = new StringBuilder("123abc");
	
		sb.append("DEF123");//Append string at the end
		sb.insert(6, "xxx");//Inserts a string at the specified subscript
		sb.setCharAt(3, 'A');//Replaces the character on the specified subscript
		sb.replace(6, 9, "aaaa");//A string that is replaced from the start subscript (inclusive) to the end subscript (exclusive)
		sb.deleteCharAt(1);//Deletes the character on the specified subscript
		sb.delete(5, 11);//Delete the string from the start subscript (inclusive) to the end subscript (exclusive)
		sb.reverse();//Reverse string
		
		//321FEDcbA31
		System.out.println(sb);

	}
}

The difference between StringBuffer and StringBuilder

StringBuffer: thread safe and inefficient
StringBuilder: thread unsafe and efficient

3, Regular expression

Meaning: used to describe or match a series of strings that conform to a statement rule

Patter n: represents the matching pattern of the regular expression

Matcher: provides grouping support for regular expressions and multiple matching support for regular expressions

character
xCharacter x
\\Backslash character
\tTab ('/ u0009')
\nNew line (newline) character ('/ u000A')
\rCarriage return ('/ u000D')
\eEscape character ('/ u001B')
.Any character
Character class
[abc]a. b or c (simple class)
[^abc]Any character except a, b or c (negative)
[a-zA-Z]A to Z or a to Z, both letters included (range)
[a-d[m-p]]A to d or m to P: [a-dm-p] (Union)
[a-z&&[def]]d. e or f (intersection)
[a-z&&[^bc]]a to Z, except b and c: [ad-z] (minus)
[a-z&&[^m-p]]A to Z, not m to p: [a-lq-z] (minus)
predefined character classes
.Any character (may or may not match the line terminator)
\d | number: [0-9]`
\D | non numeric: [^ 0-9]`
\s| white space character: [/ t/n/x0B/f/r]`
\s | non white space character: [^ / s]`
\w| word character: [a-zA-Z_0-9]`
\W | non word characters: [^ / w]`
Boundary matcher
^Start of line
$End of line
\b`Word boundary
\B`Non word boundary
\A`Start of input
\GEnd of last match
\Z`The end of the input, only for the last Terminator (if any)
\z`End of input
Greedy quantifier
X?10. Once or not
X*10. Zero or more
X+10. One or more times
X{n}10. Exactly n times
X{n,}10. At least n times
X{n,m}10. At least n times, but not more than m times

Case: replace the phone number in a string with 130 * * * 1111

package com.dream.regex_class;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test01 {
	
	public static void main(String[] args) {

		String str = "Little red 15922254658 little green 13366482269";
		
		//String of regular expression
		String regex = "(\\d{3})(\\d{4})(\\d{4})";
		
		String replaceAll = str.replaceAll(regex, "$1****$3");
		
		//Underlying principle:
//		Pattern pattern = Pattern.compile(regex);// Gets the object of the regular expression
//		Matcher matcher = pattern.matcher(str);// Matching results
//		String replaceAll = matcher.replaceAll("****");// replace	
		System.out.println(replaceAll);
	}
}
/*
	Output results:
		Small red 159 * * * * 4658 small green 133 * * * * 2269
*/

Case: check QQ email

package com.dream.regex_class;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test02 {
	
	public static void main(String[] args) {

		String str = "456123789@qq.com";
		
		//String of regular expression
		String regex = "\\d{5,10}@qq.com";
		
		boolean matches = str.matches(regex);
		//Underlying principle:
//		Pattern pattern = Pattern.compile(regex);// Get regular expression object
//		Matcher matcher = pattern.matcher(str);// Get matching results
//		boolean matches = matcher.matches();// Determine whether it matches exactly
		System.out.println(matches);
	}
}

Case: separating paths

package com.dream.regex_class;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test03 {
	
	public static void main(String[] args) {
		
		String str = "C:\\resources\\Japan and South Korea\\Study every day.avi";
		
		//String of regular expression
		String regex = "\\\\";
		
		String[] split = str.split(regex);
		//Underlying principle
//		Pattern pattern = Pattern.compile(regex);// Gets the object of the regular expression
//		String[] split = pattern.split(str);// separate
		
		for (String string : split) {
			System.out.println(string);
		}	
	}
}
/*
    Output results
        C:
        resources
        Japan and South Korea
        Study every day avi
*/

Case: find the image path in the code

package com.dream.regex_class;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test04 {
	
	public static void main(String[] args) {

		String str = "<img src='hhy/aaa.jpg'/><div><div/> <input type='image' src='submit.gif' /><img src='bbb.jpg'/>";
		
		//String of regular expression
		String regex = "<img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg)\\b)[^>]*>";
		
		//Get regular expression object
		Pattern pattern = Pattern.compile(regex);
		//Gets the object that matches the result
		Matcher matcher = pattern.matcher(str);
		
//		System.out.println("whether the whole string matches:" + matcher. Matches()); false
//		System.out.println("match at the beginning of the string:" + matcher.lookingAt()); true
//		System.out.println("whether there is a match in the string:" + matcher.find()); true
		
		//Traversal search
		while(matcher.find()){
			String group = matcher.group(2);//Get matching results
			System.out.println(group);
		}
	}
}
/*
	Output results:
		hhy/aaa.jpg
		bbb.jpg
*/

Summary:
Pattern works with Matcher
Matcher class provides grouping support for regular expressions and multiple matching support for regular expressions
Using Pattern alone can only use Pattern Matches (string regex, charsequence input) is the most basic and simplest match.
1. Regular expressions are actually used to verify email, verify mobile phone number and replace string
2. Regular expressions hardly need to be written by ourselves, just Baidu

4, Time class

1. Date class

java. util. The date class represents a specific moment, accurate to milliseconds.

package com.dream.datetime_class;

import java.util.Date;

public class Test01 {
	
	public static void main(String[] args) {

		Date date = new Date();
		//Week month date hour: minute: second time zone year
		//Thu Aug 05 11:23:00 CST 2021
		System.out.println(date); //Output current time
		
		//Since January 1970 1 0:0:0 push back 1000 milliseconds
        //Date date = new Date(1000);
        //System.out.println(date);   The output result is Thu Jan 01 08:00:01 CST 1970
	}
}

2. SimpleDateFormat class

Format the displayed date information

package com.dream.datetime_class;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test02 {
	
	public static void main(String[] args) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
		
		//Convert Date to string
		String format = sdf.format(new Date());
		System.out.println(format);  // August 5, 2021 14:36:12
		
		///Convert string to Date
		Date date = sdf.parse(format);
		System.out.println(date); //Thu Aug 05 14:36:12 CST 2021
	}
}

3. Calendar

package com.dream.datetime_class;

import java.util.Calendar;

public class Test03 {
	
	public static void main(String[] args){

		//Gets the object of the calendar class
		Calendar c = Calendar.getInstance();
		
		//Get single calendar information
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH)+1;//Month 0 ~ 11
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		
		System.out.println(year);
		System.out.println(month);
		System.out.println(day);
		System.out.println(hour);
		System.out.println(minute);
		System.out.println(second);		
	}
}

5, Math class

The Math class provides a series of methods for basic mathematical operations and geometric functions.

The Math class is a class, and all its member variables and member methods are static.

1. Constants and common methods of math class

Constant:

Constant modificationConstant name
static doublee is closer than any other value to the double value of e (the base of the natural logarithm).
static doublepi is closer than any other value to the double value of pi (the ratio of circumference to diameter of a circle).

Common methods: all methods in Math are static.

Method namemeaning
double sin (double a)Calculate the sine of angle a
double cos (double a)Calculate the cosine of angle a
double pow (double a, double b)Calculate the power b of a
double sqrt (double a)Calculates the square root of a given value
int abs (int a)Calculates the absolute value of int type value a, and also receives parameters of type long, float, and double
double ceil (double a)Returns the double value of the smallest integer greater than or equal to a
double floor (double a)Returns the double value of the largest integer less than or equal to a
int max (int a, int b)Returns the larger of int values a and b, and also receives parameters of types long, float, and double
int min(int a, int b)Returns the smaller of int values a and b, and also receives parameters of types long, float, and double
int round(float a)Rounding returns an integer
double random()Returns a double value with a positive sign, which is greater than or equal to 0.0 and less than 1.0
package com.dream.math_class;

public class Test01 {
	
	public static void main(String[] args) {

		System.out.println("Square:" + Math.pow(3, 2));//9.0
		System.out.println("Square root:" + Math.sqrt(9));//3.0
		System.out.println("Absolute value:" + Math.abs(-100));//100
		System.out.println("Round up:" + Math.ceil(1.001));//2.0
		System.out.println("Round down:" + Math.floor(1.99));//1.0
		System.out.println("Maximum value:" + Math.max(10, 20));//20
		System.out.println("Minimum value:" + Math.min(10, 20));//10
		System.out.println("rounding:" + Math.round(1.4));//1
		System.out.println("Get random value (0 contains~1 (not included):" + Math.random());
	}
}

Demand: random integer of 1 ~ 100

System.out.println((int)(Math.random()*100) + 1);

Interview question: math Is it possible for abs() to return a negative number?

System.out.println(Math.abs(Integer.MAX_VALUE+1)); //Output - 2147483648

2. Static import

When using static methods or static variables in a class, you need to write the class name every time. If you don't want to write the class name and want to write the method name or variable name directly, you can consider using static import

Syntax: import static package name Class name. *// Import all static methods and constants under this class

For example: import static Java lang.Math.*; // Import all methods and variables under math (including constants)
The aspect and variable names can be used directly in the code without the prefix Math.

package com.dream.math_class;

//Static import: import all static properties and methods in Math class into Test04, and consider the imported static properties and methods as Test04's own content
import static java.lang.Math.*;

public class Test04 {
	
	public static void main(String[] args) {

		System.out.println("Square:" + pow(3, 2));//9.0
		System.out.println("Square root:" + sqrt(9));//3.0
		System.out.println("Absolute value:" + abs(-100));//100
		System.out.println("Round up (ceiling):" + ceil(1.001));//2.0
		System.out.println("Round down (floor):" + floor(1.99));//1.0
		System.out.println("Maximum value:" + max(10, 20));//20
		System.out.println("Minimum value:" + min(10, 20));//10
		System.out.println("rounding:" + round(1.4));//1
		//Disadvantages of static import: low readability
		//If this class has the same method as the static import class, the method in this class will be called nearby
		System.out.println("Get random value (0 contains~1 (not included):" + random());//At this time, the output is no longer a random number, but 100
	}
	private static int random() {
		return 100;
	}
}

6, Random class

Create a Random class object

This class is used to generate random numbers:
Random(); // Create a new random number generator
Random(long seed); //seed number

package com.dream.random_class;

import java.util.Random;

public class Test01 {
	
	public static void main(String[] args) {
		//Create objects of random classes
		Random ran = new Random();
		
		int nextInt1 = ran.nextInt();
		System.out.println("Random out int Number in value range:" + nextInt1);
		
		int nextInt2 = ran.nextInt(10);
		System.out.println("Random 0~9 Number of:" + nextInt2);
		
		boolean nextBoolean = ran.nextBoolean();
		System.out.println("Random out boolean Value:" + nextBoolean);
	}
}

Case: random roll call device

package com.dream.random_class;

import java.util.Random;

public class Test02 {
	
	public static void main(String[] args) {
		
		//Create objects of random classes
		Random ran = new Random();
		
		String[] names = {"Zhang San","Li Si","Wang Wu","Xiao Ming","Little fat","Akun","Afan"};
		
		int index = ran.nextInt(names.length);

		System.out.println(names[index]);
	}
}

Go deep into Random

Write a simple random number class (the algorithm for calculating random numbers is just a test)

package com.dream.random_class;

public class MyRandom {
	
	//Number of seeds
	private long seed;
	
	public MyRandom() {
		//seedUniquifier() ^ System.nanoTime() gets a relatively random number of seeds
		this(seedUniquifier() ^ System.nanoTime());
	}
	public static long seedUniquifier(){
		long current = System.currentTimeMillis();
		for(;;){
			current += current*5/3+3;
			if(current%4==0 || current%7==0){
				return current;
			}
		}
	}	
	public MyRandom(long seed){
		this.seed = seed;
	}	
	public int nextInt(){
		return (int) seed;
	}	
	public int nextInt(int i){
		return Math.abs((int) seed) % i;
	}
}
package com.dream.random_class;

import java.util.Random;

public class Test03 {
	
	public static void main(String[] args) {

		//Note: random depends on the number of seeds. The number of seeds is fixed, and the random data is also fixed
		
		Random ran = new Random();
		System.out.println(ran.nextInt());
		System.out.println(ran.nextInt(100));
		
		System.out.println("--------------");
		
		MyRandom myRandom = new MyRandom();
		System.out.println(myRandom.nextInt());
		System.out.println(myRandom.nextInt(10));	
	}
}

7, Runtime class

1. Runtime represents the runtime environment of a Java program. You can get the current runtime through the getRuntime method.

2. An application cannot create a Runtime object by itself. You can obtain the Runtime object through the Runtime static method getRuntime().

3. The Runtime class can access relevant information, such as the number of processors, memory information, etc

package com.dream.runtime_class;

public class Test01 {
	
	public static void main(String[] args) {
        
		//Get runtime environment object
		Runtime run = Runtime.getRuntime();
		
		System.out.println("Get maximum memory(byte): " + run.maxMemory());
		System.out.println("Gets the number of free memory(byte): " + run.freeMemory());
		System.out.println("Number of get processes:" + run.availableProcessors();	
	}
}

8, System class

package com.dream.system_class;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class Test01 {
	
	public static void main(String[] args) {
		
		//System standard input stream (direction: console - > program)
		InputStream in = System.in;
		
		Scanner scan = new Scanner(in);
		String next = scan.next();
		
		//System standard output stream (direction: Program - > console)
        PrintStream out = System.out;
        out.println(next);
		
		//System standard error output stream (direction: Program - > console)
		PrintStream err = System.err;
		err.println(next);
		
		//close resource
		scan.close();		
	}
}

out and err of System

out and err are two threads. Whoever preempts CPU resources first will run

It shows that the multithreaded program has strong randomness

package com.dream.system_class;

public class Test02 {
	
	public static void main(String[] args) {

		System.out.println("Xiao Ming");
		System.err.println("Xiao Hong");
		System.out.println("cockroach");
	}
}
/*
	The output is very random
	But Xiaoming will output before Xiaoqiang
	out And err are equivalent to two threads. These two threads will preempt CPU resources. If err preempts first, it will output Xiaohong first. Otherwise, it will output Xiaoming first. After Xiaoming outputs Xiaohong, if Xiaoqiang grabs it, the output result may be Xiaoming, Xiaohong and Xiaoqiang. You may try to run to see the result
*/

Topics: Java