Common classes, File operations

Source: Internet
Author: User
Tags finally block try catch

Exception and exception handling

Introduction to Exceptions

In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable the exception propagation mechanism available in the specified code to transmit the commonality of any problem through the Java application.

Handling Exception Mechanisms

In a Java application, the exception handling mechanism is: Throw an exception, catch an exception.

    1. Throw exception: When a method throws an exception with an error, the method creates the exception object and delivers the runtime system, which contains exception information such as the type of exception and the state of the program when the exception occurred. The runtime system is responsible for finding and executing the code that handles the exception.
    1. Catch exception: After the method throws an exception, the runtime system will look for the appropriate exception handler (exception handler). A potential exception handler is a collection of methods that persist in the call stack, in turn, when an exception occurs. An appropriate exception handler is the exception type that can be handled by the exceptions handler when it matches the type of exception thrown by the method. The runtime system starts with the method in which the exception occurred and then turns back to the method in the call stack until it finds the method that contains the appropriate exception handler and executes it. The runtime system terminates when the runtime system traverses the call stack without finding an appropriate exception handler. At the same time, it means the termination of the Java program.
catching exceptions using the Try-catch statement

try {

program code that may occur with exceptions

} catch (Type1 id1) {

Catch and dispose of the exception type thrown by the try Type1

}

catch (Type2 Id2) {

Catch and dispose of the exception type thrown by the try Type2

}

A pair of curly braces after the keyword try will wrap a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method has an exception during the run. Running exceptions out of the monitoring area, the Java Runtime system attempts to find matching catch words to catch exceptions. If there is a matching catch clause, the exception-handling code is run and the Try-catch statement ends.

The principle of matching is that if the thrown exception object belongs to the exception class of the Catch clause, or to the subclass of the exception, the resulting exception object is considered to match the exception type of the catch block that does not live.

Summary

Try block: Used to catch an exception. You can then pick up 0 or more catch blocks, and if there is no catch block, you must follow a finally block.

Catch BLOCK: The exception that is used to handle a try catch.

Finally block: The statements in the finally block are executed regardless of whether the exception is caught or handled. When a return statement is encountered in a try block or catch block, the finally statement block is executed before the method returns. In the following 4 special cases, the finally block is not executed:

A) An exception occurred in the finally statement block.

b) exit the program with System.exit () in the previous code.

c) The thread on which the program is located dies.

d) turn off the CPU.

throws throws an exception

If a method may have an exception, but is not able to handle the exception, you can declare the exception by using the throws clause at the method declaration.

The throws statement declares the type of exception to be thrown by the method when the method is defined, and if it throws a exception exception type, the method is declared to throw all exceptions. Multiple exceptions can be separated using commas.

The syntax format for the throws statement is:

MethodName throws Exception1,exception2,.., Exceptionn

{

throw new Exception ("Exception description");

}

The throws Exception1,exception2 after the method name is,..., exceptionn to declare the list of exceptions to be thrown. When the method throws an exception to the exception list, the method does not handle exceptions for those types and their subclass types, and throws the method that invokes the method, which is handled by him.

Custom Exceptions

Use the Java built-in exception class to describe most of the exceptions that occur during programming. In addition, users can customize exceptions. User-defined exception class, just inherit the exception class.

The use of custom exception classes in your program can be broadly divided into the following steps.

(1) Create a custom exception class.

(2) throws the exception object through the Throw keyword in the method.

(3) If the exception is handled in the method that currently throws the exception, it can be captured and processed using the Try-catch statement, otherwise the exception that is thrown to the method caller is indicated by the throws keyword at the declaration of the method, and proceed to the next step.

(4) Catch and handle exceptions in the caller of the exception method.

the exception chain in Java

When the Try-catch do the specific processing, in the catch part does not do the specific processing but only with throw the keyword will be thrown out of the initiative. And then throws through the keyword

Continue to throw the method exception. It will often catch an exception and run out of another exception, and want to save the original information, which is called the anomaly chain.

strings in Java

In Java, strings are treated as objects of type string. The string class is located in the Java.lang package. By default, the package is automatically imported into all programs.

1, the Java string invariance. A string object cannot be modified after it is created, and is immutable, so-called modification is actually creating a new object that points to a different memory space. (each time new string is a new object, even if the contents of the two string are the same.) Use "= =" to compare to false, use the "equals" method if only the content is the same. If it is a character constant that occurs more than once, the Java compiler creates only one.

common methods of string classes in Java

    1. The index of characters in the string Str starts at 0 and ranges from 0 to Str.length () –1;

When using indexof () for character or string lookups, returns 1 if the match returns the position index;

When using substring (begininsex, endIndex) for string interception, the characters that include the beginindex position are not included in the EndIndex position.

The difference between "= =" and the Equals () method: "= =" Determines whether the first address of two characters in memory is the same, and whether it is the same string object, and the Equals () method compares the contents of the two string object with respect to whether the content is consistent.

the StringBuilder class in Java

In Java, in addition to using the string class to store strings, you can also use the StringBuilder class to store strings. When a string is frequently manipulated, additional temporary variables are generated. Use StringBuilder or StringBuffer to avoid this problem.

StringBuilder and StringBuffer differences: StringBuffer is thread-safe, while StringBuilder does not implement thread-safe functionality, so performance is slightly higher.

Common methods of the StringBuilder class:

wrapper classes in Java

The Java language is an object-oriented language, but the basic data types in Java are not object-oriented. Java provides a wrapper class for each base data type, so that you can manipulate the base data type as you would an object.

Correspondence between the base type and the wrapper class:

The wrapper class provides two main types of methods:

    1. A method for converting this type and other base types.

The method of converting string-type and wrapper-class to each other.

Features of the Inter Packaging class:

Construction Method:

Common methods:

Conversion between Java basic types and wrapper classes

The basic type and the wrapper type often need to be converted to each other. With the introduction of the automatic boxing and unpacking mechanism in JDK1.5, the conversion between the wrapper class and the base type is easier and more convenient.

Boxing: The basic type is converted to a wrapper class, so that it has the nature of the object, but also can be divided into manual boxing and automatic boxing.

Unpacking: The wrapper class object is converted into a basic type of value, divided into manual unpacking and automatic unpacking.

conversions between basic types and strings in Java

There are three ways to convert a base type to a string:

    1. Use the wrapper class ToString () method;

Use the valueof () method of the String class;

Using an empty string with the base type, you get the string that corresponds to the base type data.

To convert a string to a base type:

    1. Call the Parsexxx static method of the wrapper class;
    2. The valueof () method of the calling wrapper class is converted to a wrapper class of the base type, which is automatically unboxing.
using the date and SimpleDateFormat classes to represent time

The most important function of the date class in the Java.util package is to get the current time (the object created using the default parameterless construction method of the date class represents the current time).

The SimpleDateFormat class in the Java.text package formats the date.

    1. Use the format () method to convert the date to text in the specified format.

Use the parse () method to convert the text to a date.

Attention:

    1. A conversion exception may occur when invoking the parse () method of the SimpleDateFormat object, or parseexception, so exception handling is required.
    2. You need to import the Java.util package when using the date class. You need to import the Java.text package when using SimpleDateFormat.
Application of Calendar class

The most important function of the date class is to get the current time, and the calendar class handles time and date. The Java.util.Calendar class is an abstract class that can get a calendar object through the getinstance () static method, which is initialized by the current datetime, which means the current time by default, such as Calendar C = Calendar.getinstance (); Call the getinstance () method of the Calendar class to get an instance, and then get the datetime information by calling the Get () method, which is the value of the field that is required or obtained, Calendar.year the static constants defined for the Calendar class.

The Calendar class provides the GetTime () method for getting the date object, completing the conversion of the calendar and date, and the Gettimemillis () method to get the time value of this calendar, in milliseconds.

manipulating data using the Math class

The math class is located in the Java.lang package and contains methods for performing basic mathematical operations, all methods of the math class are static methods, so you can use the class name directly when using the methods in that class. Method names, such as Math.Round (); Common methods:

The collection framework in Java

the role of the collection

Within the class, the data is organized;

Simple and fast search for large numbers of entries;

There is a collection interface, which provides a series of ordered elements, and can quickly insert or delete the relevant elements in the middle of the sequence;

Some collection interfaces provide a mapping relationship that can be used to quickly find the corresponding unique object by keyword (key), which can be any type to find the specific object being mapped.

comparison of collections and arrays

The length of the array is fixed and the length of the set is variable;

Arrays can only access elements through the following table, types are fixed, and some collections are available through arbitrary.

Java Collection Framework

The Java Collection schema supports three types of collections: Rule set (set), Current table (list), and diagram (map), respectively, defined in Set,list,map. A set instance stores a set of distinct elements (collections), a list instance stores a set of ordered elements (tables), and a map stores the mapping of the physician-directed object-the key value.

Collection interface:

Set interface:

HashSet Concrete Class

Linkedhashset Concrete Class

TreeSet Concrete Class

List interface:

ArrayList Concrete Class

LinkedList Concrete Class

Vector class vectors specific classes

Stack Concrete Class

Map interface:

HashMap class

Linkedhashmap class

TreeMap class

The concrete framework is as follows:

list interface and its implementation class-arraylist

A list is a set of elements that are ordered and can be duplicated, called a sequence

The list can precisely control where each element is inserted, or remove elements from a position

arraylist-array sequence, which is an important implementation class of List

ArrayList the bottom layer is an array implementation.

Common classes, File operations

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.