Object class
The Object class is the ultimate parent class of all classes, even if the parent class of a class is not declared as Object
Then its ultimate ancestor must be Object
Under the java.lang package in the API
public final native Class<?> getClass();
It is equivalent to obtaining the most essential data type of the object
public native int hashCode();
Returns the value of the hash code of the object. If the class does not override the hashCode
The default value of hashCode is the real physical address of the object in heap memory
public boolean equals(Object obj) { return (this == obj); }
Object equals is the address value of its own object this and the incoming object obj
If you need to redefine equals, you can override subclasses and compare as needed
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
The toString of the Object itself returns the name of the most essential data type of the Object + "@" + the hexadecimal form of the hash value
If you need to redefine the string form of the object, you can override the subclass and splice the data as needed
protected native Object clone()
Copy of object
For any object x
Expression: X. clone()= X is true
[ensure that new objects are created]
The expression: x.clone().getClass() == x.getClass() is also true, but these are not the requirements that must be met.
[ensure that the data types between the object and the copy are consistent]
Generally, x.clone().equals(x) is true, but this is not a requirement to be met.
[ensure that the data content between the object and the copy is consistent]
Basic data type wrapper class
The basic data type packaging class is based on the idea that everything is an object
Take our original basic data types as classes and objects
byte-Byte short-Short int-Integer long-Long float-Float
double-Double char-Character boolean-Boolean
The main usage scenario is the conversion between basic data and string
Convert basic type to string
Convert string to base type
As shown in the IntegerDemo code
StringBuilder and StringBuffer
Are buffered strings of the String class
The feature is that you can change its size or add, delete, modify and query the string
character string
1. Both literal and new are string objects
2. Once a string is created, its length cannot be changed (the bottom layer is a character array)
3. The content cannot be changed (if you really want to change the content, you can only recreate the string)
4. In essence, the bottom layer of a string is a character array with immutable length and immutable content!
See StringDemo and string memory diagram for details
StringBuilder inherits from AbstractStringBuilder and implements CharSequence and Serializable
AbstractStringBuilder implements the extendable interface. The method to be implemented is append()
AbstractStringBuilder implements CharSequence character sequence interface (the same as the definition of List in data structure)
You can see that the constructor of StringBuilder is to create a character array with a default capacity of 16
With the increase of subsequent content, the bottom layer is dynamically expanding
void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2; if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity; if (newCapacity < 0) { if (minimumCapacity < 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); }
To put it bluntly, StringBuilder is a String with variable length and modifiable content
For specific and detailed StringBuilder methods, refer to the API
StringBuffer is basically the same as StringBuilder
StringBuffer is thread safe -- it is not easy to make mistakes in multithreaded and single threaded environments
StringBuilder is thread unsafe -- it is easy to make mistakes in multi-threaded environment and not easy to make mistakes in single threaded environment
From the perspective of code, most member functions in StringBuffer are decorated with synchronized keyword, and most member functions in StringBuffer are decorated with synchronized keyword
StringBuilder is equivalent to a person going to the bathroom at home. Generally, the door will not be locked, and generally, it will not judge whether there is anyone in the bathroom
StringBuffer is equivalent to that when you go to the toilet on the train, you usually lock it back, and people usually judge whether there is anyone in the toilet
In the case of single thread, StringBuilder is more efficient than StringBuffer because there is no need to judge the lock
In the case of multithreading, StringBuffer is safer than StringBuilder because it needs to judge the problem of lock
BigInteger and BigDecimal
In Java, the longest integer in the basic data type is long type, 8 bytes, 64 bits - 2 ^ 63 ~ 2 ^ 63 - 1
What if our data in practical application exceeds this range?
BigInteger specializes in large integer operations
BigDecimal specializes in large decimal operations
In fact, the bottom layer of BigInteger uses an immutable array to maintain and calculate the data we store
If new data is obtained through operation, a new BigInteger object is returned
Refer to API for specific methods
The bottom layer of BigDecimal is actually composed of BigInteger and decimal record scale
123.4567 : BigInteger(1234567) + scale(4) = 123.4567
regular expression
It is not only Java technology, but also exists in any programming language. It is a general IT technology
Its concept and usage are basically the same in any programming language, except for some grammatical differences caused by different languages
Regular expressions, which are mainly used to match (find and replace count) the data in a string, are also called text matching technology
// Given a string "13088889090", how to judge whether it is a mobile phone number? public boolean isPhoneNumber(String s) { if (s.length() != 11) { return false; } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }
For solving the above problems, we only solve the problem of length, and the content must be numeric characters
However, for the special number of mobile phone number
Can bit 1 be 0?
The first three digits indicate the corresponding company (China Unicom mobile telecom) 123 109 110??? The first three, it's not really random
To write code for each judgment logic is too cumbersome. Regular expressions are used to solve these problems!
If you use a regular expression to match the phone number
public boolean isPhoneNumber(String s) { //It is determined that the length is 11 and must be numeric characters return s.matches("\\d{11}"); }
From the current point of view, the solution of the problem has indeed become simpler, and the difficulty of code readability has come up
In the Java standard library, the regular expression engine is built in the java.uitl.regex package, which is very convenient to use in Java programs
The regular expression used is a string describing the rules, so we only need to write the correct rules, and we can make the regular expression
The engine can judge whether the target string conforms to the rules.
For example, to judge a "20##" year, we write the following rules:
A 4 character: 2 0 0 ~ 9 any number 0 ~ 9 any number
Corresponding regular expression: 20\d\d, where \ d represents the meaning of any number
However, in Java, regular expressions should be represented by strings, "20\d\d" is wrong because '' is an escape character in Java
It should end up saying "20\d\d"
Matching rules
The matching rules of regular expressions are matched from left to right
Let's first look at how to use regular expressions for exact matching
For the regular expression abc, it can only exactly match the string "abc", not "ab", "abc" and "abcd"
If a regular expression wants to match a special character, it needs to be escaped with the 'escape character
Regular expression a \ & C, where \ & is used to match the special character '&', which can exactly match "A & C"
The regular expression "a \ & C" used to match in java
If you want to match Chinese, use \ u###### to match Chinese regular expression a\u548cc, and accurately match "a and c"
In fact, for this exact match, there is no need to use the regular string. Just use the string equals()
String regex01 = "20\\d\\d"; System.out.println("2019".matches(regex01)); System.out.println("2100".matches(regex01)); System.out.println("20AB".matches(regex01)); String regex02 = "abc"; System.out.println("abc".matches(regex02)); System.out.println("ab".matches(regex02)); String regex03 = "a\\&c"; System.out.println("a&c".matches(regex03)); System.out.println("ac".matches(regex03)); String regex04 = "a\\u548cc"; System.out.println("a and c".matches(regex04)); System.out.println("a Ha c".matches(regex04));
Match any character
In most cases, the matching rules we want are more fuzzy matching
. match any character
String regex05 = "a.c"; System.out.println("abc".matches(regex05)); System.out.println("a&c".matches(regex05)); System.out.println("acc".matches(regex05)); System.out.println("ac".matches(regex05)); System.out.println("a&&c".matches(regex05));
Match number
If we only want to match the numbers 0 ~ 9, use \ d
String regex06 = "Demo\\d\\d\\.java"; System.out.println("Demo11.java".matches(regex06)); System.out.println("Demo123.java".matches(regex06)); System.out.println("Demo.java".matches(regex06)); System.out.println("Demo12.avi".matches(regex06));
Match common characters
\d any number \ w matches any letter, number, or underscore
String regex07 = "java\\w"; System.out.println("java_".matches(regex07)); System.out.println("javac".matches(regex07)); System.out.println("java".matches(regex07)); System.out.println("java!".matches(regex07));
Match space characters
\s. The so-called space character includes the effect of tab '\ t' in addition to space '
String regex08 = "a\\sc"; System.out.println("a c".matches(regex08)); System.out.println("a c".matches(regex08)); System.out.println("ac".matches(regex08)); System.out.println("a c".matches(regex08)); System.out.println("a\tc".matches(regex08));
Match non numeric
\D any number '\ d' any non number
\S any space \ s any non space
\W any numeric letter underline '\ W' any non numeric letter underline
String regex09 = "\\d\\w\\W\\D"; System.out.println("1234".matches(regex09)); System.out.println("9w!c".matches(regex09));
Repeat matching
\d any number, if A\d can match "A0", "A1", ~, "A9"
What if multiple characters match?
// Use '*' to match any character (including 0) String regex10 = "A*"; //0 or more consecutive A's System.out.println("A".matches(regex10)); System.out.println("Animal".matches(regex10)); System.out.println("A123123".matches(regex10)); System.out.println("AAAAAAA".matches(regex10)); String regex11 = "A\\d*"; System.out.println("A12313123123".matches(regex11)); System.out.println("A".matches(regex11)); System.out.println("Aasdhjahsjdk1123".matches(regex11)); System.out.println("".matches(regex11)); // Use ` + ` to match at least one character String regex12 = "A\\d+"; System.out.println("A12313123123".matches(regex12)); System.out.println("A".matches(regex12)); System.out.println("Aasdhjahsjdk1123".matches(regex12)); System.out.println("".matches(regex12)); // Use '` You can match 0 or one character String regex13 = "A\\d?"; System.out.println("A12313123123".matches(regex13)); System.out.println("A".matches(regex13)); System.out.println("A1".matches(regex13)); System.out.println("".matches(regex13)); // If you specify the number of duplicates, use ` {n} ` to match n, use ` {n,m} ` to match n~m, and use ` {n,} ` to match at least n System.out.println("A123".matches("A\\d{3}")); System.out.println("A123".matches("A\\d{3,5}")); System.out.println("A12345".matches("A\\d{3,5}")); System.out.println("A123".matches("A\\d{4,}")); // For example, match a landline number 010-33167854 with 3 numbers - 8 numbers ` \ d{3}\-\d{8}` System.out.println("010-12345678".matches("\\d{3}\\-\\d{8}")); System.out.println("0101-2345678".matches("\\d{3}\\-\\d{8}"));
Regular expression summary:
Regular expression rules can match
A fixed character a "a"
\u548c specify Unicode characters "and"
. any character "a" "1" ""
\d a numeric character 0 ~ 9 "0" ~ "9"
\w a number or letter or underscore
\W not \ w
\Dnon \ d
\s a space character (\ t ')
\S not \ s
A* A has any "" a "" AA "" AAA "
A+ A at least one "a" "AA" "AAA"
A? A0 or 1 "" a "
A{3} A appears "AAA" 3 times
A{3,5} A appears "AAA" "AAAA" "AAAAA" 3 ~ 5 times
A{2,} A appears "AA" "AAA" "AAAA" at least twice
A{0,3} A appears 0 ~ 3 times "" a "" AA "" AAA "
Match beginning and end
Match starts with ^ match ends with$
String regex01 = "^Demo\w*\.java$";
System.out.println("Demo01.java".matches(regex01));
Match specified range
\d represents all numbers 0 ~ 9. If 0 and 1 [2-9] are not allowed
// For each bit of a hexadecimal digit [0-9a-fA-F] String regex02 = "[2-9]\\d{5}"; System.out.println("345678".matches(regex02)); System.out.println("123456".matches(regex02)); String regex03 = "[0-9a-fA-F]{4}"; System.out.println("12ab".matches(regex03)); System.out.println("wc99".matches(regex03)); /* Logical or matching rules Our content can match two regular expressions. You can use ` | 'to combine two regular expressions or `AB | CD`Indicates that it can match "AB" or "CD" How to match a string with or without programming language words */ `java|c|python|go` String regex04 = ".*java|c|python|go.*"; System.out.println("I like java".matches(regex04)); System.out.println("I like c++".matches(regex04)); use()Merge matching If you want to match"learn java" "learn php" "learn go" `learn\sjava|learn\sphp|learn\sgo` => `learn\s(java|php|go)`
Group matching
Group matching still uses (), but we generally use regular expressions, in addition to judging whether they match
You also need to extract the matching content if multiple places in a string are matched
Matching telephone \ d{3,4}-\d{6,8} area code - number "010-123456" "0110-12345678"
Extract the area code and number respectively
\d{3,4}-\d{6,8} => (\d{3,4})-(\d{6,8})
Recalling the matches method of String, the bottom layer actually creates an object Pattern about regular expression rules
Then, the rule object Pattern matches the data to generate a matching object Matcher
All matching results have a method in the Matcher. mathces() in the Matcher is the final result of judging whether the string matches the rule, boolean
Pattern p = Pattern.compile("(\\d{3,4})-(\\d{6,8})"); Matcher m = p.matcher("010-123456789"); if (m.matches()) { //The result is the entire phone number System.out.println(m.group(0)); //Get the first part of the area code System.out.println(m.group(1)); //Get the second part of the phone System.out.println(m.group(2)); }
Non greedy matching problem
Given a numeric string, judge the number of zeros at the end
"123000" 3 0
"10100" 2 0
"1001" 0 0
(\d+)(0*)
Pattern p1 = Pattern.compile("(\\d+)(0*)"); Matcher m1 = p1.matcher("123000"); if (m1.matches()) { System.out.println("group1 = " + m1.group(1)); System.out.println("group2 = " + m1.group(2)); }
Results for the above code group1 = 123000 group2 = find group2 No content For 123000, I hope to get 123000 For 10100, I hope to get 101 00 For 1001, you want to get 1001 "" Actually 123000 123000 "" Actually 10100 10100 "" `(\d+)(0*)`In fact, it is reasonable that this regular expression can get this result Regular expressions use greedy matching by default: for any rule, it matches back as much as possible therefore\d+By the way, 0 is included The problem with non greed is to let\d+Try to match as few as possible*Try to match as many as possible in the rules\d+Add later?that will do \d? Represents one or zero digits \d?? The first question mark represents one or zero numbers there, and the second question mark represents a non greedy match If`(\d??)(9*)`De matching"9999","" "9999"
Pattern p1 = Pattern.compile("(\\d??)(9*)"); Matcher m1 = p1.matcher("9999"); if (m1.matches()) { System.out.println("group1 = " + m1.group(1)); System.out.println("group2 = " + m1.group(2)); } The result is: group1 = group2 = 9999 For the original problem `(\d+)(0*)` => `(\d+?)(0*)` Pattern p1 = Pattern.compile("(\\d+?)(0*)"); Matcher m1 = p1.matcher("123000"); if (m1.matches()) { System.out.println("group1 = " + m1.group(1)); System.out.println("group2 = " + m1.group(2)); } group1 = 123 group2 = 000
Delimited string
String.split(String regex) System.out.println(Arrays.toString("a b c".split("\\s"))); System.out.println(Arrays.toString("a b c".split("\\s"))); System.out.println(Arrays.toString("a b c".split("\\s+"))); System.out.println(Arrays.toString("a , b ;; c ,,;; d , e".split("[\\,\\;\\s]+")));
The result is: [a, b, c] [a, , b, , , , , , c] [a, b, c] [a, b, c, d, e]
Search string
String s = "the quick brown fox jumps over the lazy dog"; Pattern p2 = Pattern.compile("\\wo\\w"); Matcher m2 = p2.matcher(s); while (m2.find()) { //The start and end of the Matcher are the starting positions of each matched string from left to right in the original string String sub = s.substring(m2.start(),m2.end()); System.out.println(sub); }
Replace string
String.replace String.replaceAll String s1 = "the quick brown fox jumps over the lazy dog"; s1 = s1.replaceAll("\\s+"," "); System.out.println(s1);
Back reference
If we want to replace the searched specified string according to rules, for example, if we search a string upside down and add some content before and after it
Time date
We used the function System.currentMiliis() before
This function returns the number of milliseconds since 00:00 on January 1, 1970. long type
Get this millisecond to convert the year, month, day and week
Is there a class that specifically calculates time and date? Yes
java.util.Date java.sql.Date java.sql.Time java.sql.Timestamp java.text.DateFormat java.text.SimpleDateFormat java.util.Calendar
about java.util.Date yes java.sql.Date and java.sql.Time and java.sql.Timestamp The parent class of, too Java Time standard library in It represents a specific moment from January 1, 1970 00:00 The number of milliseconds from the beginning to the present is obtained by internal calculation Specific time parameters: year, day, hour, minute and second But from JDK1.1(JDK8-JDK1.8)Start, recommended Calendar This class represents time about java.text.DataFormat It is an abstract class that represents time/Date formatting class can also extract time and convert time The time string parses the specific time, and the specific time is converted into a string representation java.text.SimpleDateFormat It is DataFormat Implementation subclasses, functions and DataFormat The same, but there will be richer operations For formatting parameters: y year yyyy year-2021 year M month MM month-11 month d day dd day-06 day `MM yyyy dd E a` - 08 2021 16 riday AM E week E-Sunday a Morning and afternoon a-PM/AM H hour(24 Hour system) h hour(12 Hour system) `HH:mm:ss` - 11:13:58 m minute s second about java.util.Calendar abstract class It is used to encapsulate calendar information (including time). Its main function is that its method can calculate the time component (based on the offset of the current time) Operations on time are mainly divided into the following categories: 1, Time and date acquisition
Date date = new Date(); System.out.println(date); //Outdated millennium bug is not recommended System.out.println(date.getHours()); System.out.println(date.getYear()); System.out.println(date.getDay()); System.out.println(date.getMonth()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = df.format(System.currentTimeMillis()); String time2 = df.format(date); System.out.println(time); System.out.println(time2);
2, Date conversion Date to string to date
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //Date to string Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime(); String s1 = sdf.format(date); System.out.println(s1); //String parse date String s2 = "2021-08-16 11:30:52"; Date date2 = sdf.parse(s2); System.out.println(date2); String to time, in Calendar To get the details DateFormat df = new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second"); Date date = df.parse("2021 August 16, 2014 14:16:52"); Calendar cal = df.getCalendar(); System.out.println(cal.getTime()); //Get the current calendar timecalendar cal = calendar. Getinstance(); int year = cal.get(Calendar.YEAR); //Acquisition year int month = cal.get(Calendar.MONDAY); //Get month int day = cal.get(Calendar.DATE); //Acquisition day int hour = cal.get(Calendar.HOUR); //When getting int minute = cal.get(Calendar.MINUTE);//Get points int second = cal.get(Calendar.SECOND); //Get seconds int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);//What day of the week int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);//What day of the year System.out.println(year + " " + month + " " + day);//month is calculated from 0 (January) System.out.println(hour + " " + minute + " " + second); System.out.println(dayOfWeek); System.out.println(dayOfYear); Get the current time display am PM Date date = new Date(); //specific date DateFormat df1 = DateFormat.getDateInstance(); System.out.println(df1.format(date)); //Mm / DD / yyyy H / min / S DateFormat df2 = DateFormat.getDateTimeInstance(); System.out.println(df2.format(date)); //Hour, minute and second DateFormat df3 = DateFormat.getTimeInstance(); System.out.println(df3.format(date)); //Monday, August 16, 2021 02:33:40 PM CST DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL); System.out.println(df4.format(date)); //August 16, 2021 02:34:44 PM DateFormat df5 = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG); System.out.println(df5.format(date)); //21-8-16 2:35 PM DateFormat df6 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); System.out.println(df6.format(date)); //2021-8-16 14:36:17 DateFormat df7 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM); System.out.println(df7.format(date));
3, Date addition and subtraction
Calculate a few days ago based on a certain date/after... Gets the time of the previous year of the current time Calendar now = Calendar.getInstance(); print(now); now.add(Calendar.YEAR,1); //It's a year from now print(now); now.add(Calendar.YEAR,-1); //It was a year ago print(now); now.add(Calendar.HOUR,-1); print(now); Calendar specialDate = Calendar.getInstance(); specialDate.setTimeInMillis(System.currentTimeMillis() / 2); print(specialDate); specialDate.add(Calendar.YEAR,-1000); print(specialDate); private static void print(Calendar cal) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(df.format(cal.getTime())); } Then add the hours, minutes and seconds according to the time SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Calendar nowTime = Calendar.getInstance(); nowTime.add(Calendar.MINUTE , -30); String s = df.format(nowTime.getTime()); System.out.println(s); Calculate the number of days from January 1, 2017 to now SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = "2017-01-01 14:52:30"; Calendar calendar = Calendar.getInstance(); long nowDate = calendar.getTime().getTime(); //Gets the millisecond value of the current time long specialDate = sdf.parse(dateString).getTime(); //Gets the millisecond value of the specified date long betweenDate = (nowDate - specialDate) / (1000 * 60 * 60 * 24);//How many days is the calculation interval System.out.println(betweenDate); Find the difference between the two dates in hours, minutes and seconds DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = df.parse("2021-08-16 15:18:23"); Date d2 = df.parse("2021-08-17 17:45:32"); long nd = 1000 * 24 * 60 * 60; //How many milliseconds a day long nh = 1000 * 60 * 60; //How many milliseconds an hour long nm = 1000 * 60; //How many milliseconds per minute long ns = 1000; //How many milliseconds per second long diff = d2.getTime() - d1.getTime(); //How many days is the difference long day = diff / nd; //How many hours is the difference long hour = diff % nd / nh; //Calculate the difference in minutes long minute = diff % nd % nh / nm; //How many seconds is the difference long second = diff % nd % nh % nm / ns; System.out.println(day + " " + hour + " " + minute + " " + second);
4, Date comparison
One is through before and after Compare, or compareTo To compare SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString1 = "2021-08-16 11:11:11"; String dateString2 = "2021-08-17 11:11:11"; Date date1 = sdf.parse(dateString1); Date date2 = sdf.parse(dateString2); System.out.println(date1.before(date2)); System.out.println(date1.after(date2)); System.out.println(date1.compareTo(date2));
abnormal
It is some errors in the running process of the program. We use the object-oriented idea to describe these errors with classes
An error occurs, that is, an error object is created, which is what we call an exception object
I've seen it before
IndexOutOfBoundsException
ArrayIndexOutOfBoundsException
Array subscript out of bounds exception subscript out of array range
StringfIndexOutOfBoundsException
The character string angle is out of bounds. The exception angle is not in the range of the character string
NullPointerException
Null pointer exception calls its member on null
ArithmeticException
Abnormal mathematical operation illegal mathematical operation
ClassCastException
The type conversion exception casts the class incorrectly
NumberFormatException
Number format exception parses the number string
InputMismatchException
Input mismatch exception. Illegal data was entered during input
ParseException
Time parsing exception illegal time format
StackOverFlowError
Stack memory overflow exception function recursion
OutOfMemoryError
Heap memory exception. The array space is too large. There are too many objects in the program
public static void main(String[] args) { int[] arr = {1,2,3,4,5}; int num = getNumber(arr,10); System.out.println(num); } private static int getNumber(int[] arr, int i) { return arr[i]; //If arr is null, null pointerexception //If i is out of bounds, ArrayIndexOutOfBoundsException }
As shown in the above code, for a function with a return value If the operation calculation is correct, there must be a normal return value If the operation calculation is wrong, will there be a normal return value from the perspective of function? can't In essence, most of the mistakes are actually made by JVM Of course, we can also judge it manually private static int getNumber(int[] arr, int i) { //return arr[i];// The judgment is made by the JVM //Simulate the operation of the JVM and simulate the automatic discovery of the JVM with manual judgment if (arr == null) { //The problem object that generated a null pointer exception //Use the throw key to inform the caller of the resulting problem throw new NullPointerException(); //Once the above raises a problem, this function immediately interrupts //Similar to return, normal end (bounce stack) //Throw abnormal end (interrupt the forced pop-up stack and throw a problem to the caller) } if (i < 0 || i >= arr.length) { //A problem object that generates an array subscript out of bounds exception throw new ArrayIndexOutOfBoundsException(); //throw new StackOverflowError(); //PS can throw out problems in case of errors, but it is best to throw the most relevant and accurate problems } return arr[i]; } getNumber If a problem occurs, it is directly thrown to the main function, but the main function does not deal with the problem. The main function then throws the problem to the caller JVM JVM I won't help you solve it. The result is that the program is interrupted! When the police found out that you had committed a crime, you wouldn't deal with it. Let your father deal with it, but your father wouldn't deal with it. Finally, he handed it over to the police and died JVM-call main-call getNumber-getNumber An exception occurred-Throw to main-main Not handled-Throw pass to JVM-JVM I'll interrupt you directly PS:Of course, if there is a problem inside the function, you can also handle the problem internally, and you don't need to throw it to the upper layer Since there are many causes of errors and many classes that describe errors, this situation leads to a large family/System, it's all there Exception error class, we call it exception system For the abnormal system, everyone is wrong, but the causes are different. We continue to extract commonalities upward, and finally Draw out Throwable This interface (which can be thrown) can be thrown whenever it is an exception object, regardless of the reason Throwable Class is Java The superclass of all errors or exceptions in the language can be passed only when the object is an instance of this class (or one of its subclasses) Java Virtual machine or Java throw Statement thrown. Throwable Error yes Throwable Subclasses that indicate that reasonable applications should not attempt to`capture`Serious problems Once this happens Error Level error, it must be the bottom level error. This kind of error is usually very serious There is no way to recover it during operation. We can only interrupt the program and let the programmer modify the code again Error There are not many subclasses, but they are all cruel Exception Class and its subclasses are Throwable A form that indicates the conditions that a reasonable application wants to capture Once this problem occurs, it can be recovered (not necessary). After recovery, it can be operated normally, and general small errors can be corrected Exception There are many subcategories, but they are all more delicious Runtime exception: RuntimeException Those who might be Java Superclass of the exception thrown during normal operation of the virtual machine May be thrown during method execution but not captured RuntimeException Any subclass of does not need to be throws Clause It means that these problems do not need to be prevented in advance (in essence, it is OK, but it is not necessary) Because the problem can be found only when it is actually running. Once a problem occurs during running, it will not be corrected, and the program will directly terminate Compile time exception: Exception And its subclasses(except RuntimeException),Exception thrown at compile time Check whether the program may have problems during compilation, and if so, take precautions: capture declarations Before you go out, you should first consider the possible problems on the road, such as: bring toilet paper for stomach pain, medicine for cold, mask, and money when you are hungry It means that these problems can be prevented in advance in two ways: capture try-catch-finally The program will not be interrupted statement throws The function is followed by the class name of the exception throw Programs that follow an exception object inside a function may break In summary: Error And runtime exceptions are basically problems that occur during operation. Once these problems occur, there is basically no room for recovery, and the program is interrupted directly But relatively speaking Error The severity of is greater than the runtime exception RuntimeException In fact, the essence is Exception Subclass of This means that it can be prevented in advance during compilation, but it's not necessary. It depends on the mood Can runtime exceptions be caught and declared? Can refer to ExceptionDemo03 Case: Mr. Zhang teaches everyone with a computer Computer - blue screen smoking reference ExceptionDemo04 try-catch-finally try The statement block contains the code that may cause problems. Try not to put irrelevant code into it, otherwise the problem of truncation will occur
try{ codeA throw ... codeB }
If an exception is thrown in throw, codeB will not be executed. It is recommended to put codeB later
The catch statement block always puts the code that has a problem and captures the post-processing problem. If the problem does not appear in the try statement block, the catch will not run
catch(Exception e) { code }
finally The statement block contains the code to be executed regardless of whether the problem exception is generated or not code
finally{ code//Close the resource (IO database network) and finish some work }
If try-catch-finally All include return reference ExceptionDemo05