Exception handling, common classes, Java collection Framework, reflection

Source: Internet
Author: User
Tags character classes finally block stack trace throwable

Exception handling:

1. Exceptions : Problems arising during the execution of the program.

Three kinds of exceptions: ① Check for exceptions: Also known as checdked or abnormal. This is usually a user error or a problem that cannot be foreseen by the programmer. Check that the exception needs to be resolved before compiling.

② Runtime Exception: The type of exception that can be avoided by programmers during the course of a program's operation.

③ error: In fact, the error is not an exception, but it is a problem that the user and programmer cannot control.

2. Abnormal control flow :

  An exception is an object that is thrown by a method.

(1) Three methods of handling exceptions: ① catches this exception and does not let it continue down the call stack.

② catches this exception and continues to throw it down.

③ does not catch this exception, causing the method to be ejected from the call stack, and the exception object continues to be thrown to the main () method below the call stack.

(2) Regardless of how many methods are in the call stack, the program control process will continue to execute downward in the call stack.

Use the printstacktrace () method to print the call stack trace information.

3. Throwable class:

(1) The three types of exceptions have a common parent class: Java.lang.Throwable, only objects of type Throwable can be thrown by the JVM. Two subcategories of Throwable: Exception and error.

The inheritance hierarchy of exceptions in the Java language is an exception-based three class.

(2) If a class is a subclass of the RuntimeException class, this subclass represents a run-time exception.

all exceptions are subclasses of the exception class; exception handling and claim rules are one that applies only to Check the basic Java functionality of the exception.

(3) The exception object is a Java object of type Throwable.

4. Catching Exceptions:  

1 Try {2      // code   that is protected 3 }catch{4     // capture block 5 }

(1) When the TRY statement block has no exception, the catch statement block is ignored.

Catch catches a special exception before catching a generic exception.

(2) A try/catch does not capture everything: a try block can be followed by multiple catch blocks

11Try{22//code that is protected39 ·Catch{44//Capture Block55}Catch{66//Capture Block77}Catch{88//Capture Block93 ·

Because exception is the parent class for all exceptions, you can use the exception class to catch all check exceptions and run-time exceptions.

5. Exception handling and claim rules:

is a strictly enforced claim rule in the Java language for checks. This rule indicates that a check exception is either handled or declared, and the rule does not apply to run-time exceptions .

1. Declaring an exception: If a method does not handle a check exception, the method must use throws to declare the exception, and the keyword throws appears at the end of the method signature .

A method can declare that it throws multiple exceptions, with multiple exceptions separated by commas.

1 public void ( double amount) throws Remote Exception, Insufficientfundsexception

2. Throw an exception: throws an exception using the throw keyword, which can be a new exception instance or the exception that you just caught. The throw statement will cause the current code to stop executing immediately, and the exception will be thrown to the previous method in the call stack.

3. finally:

Used to create a block of code after a try block, the finally code block is always executed, regardless of whether the exception occurs. Any action can be performed within a finally block.

Function: simplifies the code.

4. User-defined exceptions:

It should be noted when writing user-defined exception classes:

① all exceptions must be sub-classes of throwable;

② if we want to write a check exception that can be automatically forced by exception handling or declaration rules, we need to inherit the exception class;

③ If you want to write a run-time exception, you need to inherit the RuntimeException class.

Common classes:

1. System Related classes:

1. System class: Represents the running platform of the current Java program.

(1) The System class is a final class, and all the properties and methods of the class are static;

(2) The system class is often used for the time of execution of the language logger, copying arrays, determining the current system properties and acquiring system environment variables, etc.

(3) to forcibly terminate the virtual machine, exit the code used by the executing program: system.exit (0); 。

The runtime class represents the runtime environment of a Java program.

2. String class: Contains a immutable string

Methods for creating a String object:

(1) explicitly created using the constructor of the string object:

eg:string str = new String ("Hello");

(2) implicitly created by assigning a string constant to a variable of type string:

eg:eg:String str = "Hello";

2. StringBuffer class: Represents a variable-content string.

(1) Once the final desired string is generated by StringBuffer, it can be called by its ToString () method to convert it to a string object;

(2) StringBuffer does not generate new objects when string processing occurs, so it is better than string in memory usage.

(3) Creating a String object using StringBuffer can only be created by using the StringBuffer constructor:

Eg:eg:StringBuffer str = new StringBuffer ("Hello");

(4) StringBuffer emphasis on the change of strings, such as append, insert, delete;

(5) The Append () method of the StringBuffer class is used for string connections.

3. StringBuilder class:

Compared to StringBuffer: StringBuffer is thread-safe and StringBuilder is not, so StringBuilder performance is higher than stringbuffer

2. Wrapper class: encapsulates eight basic data types in Java into classes

When using the wrapper class, be aware that:

(1) All wrapper classes are final types and cannot create their subclasses;

(2) The packing class is immutable class.

Use the parse XXX (string s) method to convert a string to the corresponding base data type

3. Regular Expressions:

Regular expressions consist of ordinary characters, character classes, wildcard characters, and quantitative words.

Common Regular Expressions:

Regular expression matching HTML tags:< (\s*?) [^>]*>.*?</\1>|<.*? />;

Regular expressions that match the whitespace characters: ^\s*|\s*$;

Regular expression matching email address: \w+ ([-+.] \w+) *@\w+ ([-.] \w+) *\.\w+ ([-.] \w+) *;

Matches the account number is legal (the letter begins, allows 5-16 bytes, allows alphanumeric underline): ^[a-za-z][a-za-z0-9_]{4,15}$;

Match IP address: \d+\.\d+\.\d+\.\d+;

Match a specific number:
^[1-9]\d*$//Match positive integer
^-[1-9]\d*$//Match negative integer
^-? [1-9]\d*$//Match integer
^[1-9]\d*|0$//matches non-negative integers (positive integers + 0)
^-[1-9]\d*|0$//matches a non-positive integer (negative integer + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$//Match positive floating point number
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*) $//Match negative floating point number
^-? ([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0) $//Match floating point number
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$//Match non-negative floating-point number (positive floating point + 0)
^ (-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)) |0?\.0+|0$//match non-positive floating-point number (negative floating-point number + 0)

Match a specific string:
^[a-za-z]+$//Match a string consisting of 26 English letters
^[a-z]+$//matches a string consisting of 26 uppercase letters
^[a-z]+$//matches a string consisting of 26 letters in lowercase
^[a-za-z0-9]+$//matches a string consisting of a number and 26 English letters
^\w+$//matches a string consisting of a number, 26 letters, or underscores

Use regular Expressions:

eg

1 pattern  ptn   =   pattern. Compile (str); 2 Matcher  Matcher  =  ptn. Matcher (regular expression); 3 if (Matcher.matches ()) {4     System.out.println ("lawful"); 5 Else {6     SYSTEM.OUT.PRINTLN ("illegal" ); 7 }

Java Collection Framework (JCF):

The Java Collection Framework consists of a set of classes and interfaces.

(1) main function: to organize the stored data into some kind of structure and to access the data in a certain way.

Objective: To provide a common framework for working with collections of objects to reduce the amount of code the programmer handles when dealing with different sets of objects.

(2) an object that is added to the collection is called an element. Two elements are compared by using the Equals () method, and If True is returned, two elements are duplicated.

(3) The object is stored in three ways by whether it is allowed to repeat, in order, or if it is allowed to add a null element:

①set (SET): No order, no repetition;

②list (list): objects are sorted by index and can be duplicated;

③map (map): Contains a pair of "key Object-Value object" mappings, key objects cannot be duplicated, and value objects can be duplicated.

List interface:

Features: The elements in the ①list are sequential;

② allows elements to be duplicated;

③ its implementation class typically supports NULL elements;

④ accesses the elements in the List Object container by index .

Inherit from collection interface, have some methods of collection interface, commonly used ArrayList, LinkedList.

ArrayList:    represents an indexed element. Compared with the array, ArrayList has no predetermined size, its length can be increased as needed;

Generic <e>: Allows you to define a type-formal parameter when defining a class or interface, which will be determined when declaring a variable, creating an object (that is, the actual argument passed in).

Eg:arraylist<integer> al = new Arraylist<integer> ();

Role: Use generics to type parameters to achieve type-safe parent purpose, and to eliminate the movement of data from the collection in the transformation.

Iterator traversal:

Iterator it = name. Iterator ();

while (It.hasnext ()) {

Object obj = It.next ();

System.out.println (obj);

}

    linkedlist: A list of two-way linked lists is implemented.

①arraylist is implemented as an array, and the query efficiency is high.

The ②linkedlist is realized by the chain list method, and is used for frequent additions and deletions;

③vector: Similar to ArrayList, is thread-safe with performance below ArrayList.

linkedlist > ArrayList > Vector  

Set interface:

Features: ① cannot contain duplicate elements;

② may have order or may not be in order;

③ elements may be ordered unordered, so the elements in the set cannot be accessed with an index.

Common classes for implementing set interfaces: HashSet, TreeSet.

Hashset:① the elements without order;

② does not allow duplicate elements to appear;

The ③ allows the inclusion of a null element.

TreeSet: Ensure that the objects in the collection are sorted in a certain order, and by default the natural sort is used.

Natural sort: Sorted by collection element size, ascending order;

Custom sort: Sort by a specific comparer (you must use the comparator interface, and you must overwrite the Cimpare (object O1, Object O2) method that you want to deposit to the object in TreeSet.

Map interface:

It corresponds to a collection of correspondence between the key (key) and the value (value). Key-value single-to-one relationships, both of which can be of any type.

HashMap class: Is a hash algorithm based on the implementation of the map interface, the key is unique.

To create a new HashMap:

Eg:map <string, string> Map = new hashmap<string, string> ();

Reflection:

1. The loading of the class is done by the loader, and the JVM itself contains a classloader ———— root class Loader

(1) The root class loader loads the core Java class;

(2) Extending the class loader to load the extended Java class;

(3) The System class loader records the class of the application itself.

2. Connection: After the class is loaded, the system creates a corresponding class object, then enters the connection phase, which is responsible for merging the binary data of the class into the JRE;

Three stages: ① validation, ② preparation, ③ parsing.

3. Initialize: The JVM is responsible for initializing static properties

Two ways to initialize: ① Specifies the initial value when declaring a static property;

② uses static initialization blocks to specify initial values for static properties.

reflection : In Java, it can be loaded at runtime to detect a class that uses a completely unknown compilation period.

To view class information using reflection:

There are three ways to get a class object:

1. forname static method:

Eg:class C = Class.forName ("Permission class name");

2. Call the class property of a class name when it is known at compile time

The Eg:class c = class name. class;

3. Call the object's GetClass () method to return the class object to which the object belongs

Eg:class C = Object name. GetClass ();

Exception handling, common classes, Java collection Framework, reflection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.