Get started with Java 04

Source: Internet
Author: User
Tags modifier

1. Abnormal system :
---------| Throwable
--------------| Error (Error) errors are generally caused by JVM or hardware problems, so we generally do not deal with the code.
--------------| Exception (Exception) exceptions we usually deal with the code.

----------------------| run-time Exception: method can not be declared, can not handle

----------------------| compile-time exception: must declare that the caller must handle the exception


(1) How to handle abnormal

Mode one: Capture processing

Format of capture processing

try{

Code that might have occurred an exception

}catch (catch exception type variable name) {
Code to handle exceptions
}

Capture the details of the processing to be noted:
1. If there is an exception code in a try block, after processing, the code outside the Try-catch block will execute normally.
2. If the code for the exception appears in a try block, the statement after the exception in the try block cannot be executed.
3. A try block can be followed by multiple catch blocks, that is, a try block can catch a variety of types of exceptions, but the captured
The exception type must be captured from small to large.

Mode two: Throw processing (throw throws)


Throw the details of the processing to note:
1. If a method internally throws a compile-time exception object, the method must be declared thrown.
2. If you call a method that declares a compile-time exception to be thrown, the caller must handle it.
3. If a method throws an exception object, the method also stops immediately (a method encounters the Throw keyword and the method stops immediately)
4. In one case, only one exception object can be thrown.

The Throw keyword is used to throw an exception object within the body of the method, and throws is used to declare the exception type on the method declaration.

(2) Custom exception classes

Requirements: Analog Xiaoping Line when not plugged in, this time throws an exception

Step: A. Defining an exception class requires inheriting the exception class (some classes are not clear to see the API documentation)

// defining an Exception class class extends exception{      public  noipexception (String message) {            Super (message); // calling the parent class constructor       }}
View Code

B. There is now a method call that can occur when this exception declares this exception, and this method we put it in a test class

classtest{PUBLCStatic voidMain (string[] args) {String IP= "192.1.1.124"; IP=NULL; Try{FANGFA (IP);//This method may cause an exception to be declared when the method is defined}Catch(noipexception e) {System.out.println ("Please plug in the network cable!" ")}         Public Static voidFANGFA (String IP)Thrownoipexception{if(ip==NULL)              {ThrowNoipexception ("No cable inserted boy")} System.out.print ("Normal display")        }    }}
View Code

Summary: Calling a method may occur an exception-the "Custom This exception-" method declares this exception-"Method body write-up is the case to throw this exception

(3) Final can release code resources

try{

}catch () {}

finally{

This is always done only when you execute a try

}

(4) Permission modifier: the permission modifier is the scope visibility of the member that controls the adornment.

(5) Jar Packaging

A. Role: 1. User-friendly fast running of a project

2. Provide tool classes for others to use in the form of jar packages

These tool classes can be seen in the extract file, all packaged with jars

B. Usage:

Jar CVF jar file name class file or folder

Precautions:

1. After a program is packaged, you need to specify the entry class on the manifest file, in the format: Mian-class: Package name. class Name

2. When using, can only open the image session interface, cannot open the console program

Example:

(6) Common methods of the object class:

ToString (); Returns the string representation of the object. Returns a string that describes the object.
Question: How does toString () work? After overriding toString, when we output an object directly, we will output the format data that meets our needs; we can try Object.ToString () to see the result: The result is a class full name +hashcode value

Equals (object obj) is used to compare the memory addresses of two objects and to determine whether two objects are the same object.

Hashcode () returns the hash code value of the object (you can interpret the hash code as the memory address of the object)/


Specification in Java: generally we rewrite the Equals method of a class, and we all rewrite its Hashcode method.

Java is open source .... Source Code Disclosure ...

How to view the source code:
Mode one: Hold down the CTRL key and click the source code you want to see.

Mode two: Move the cursor to the point where you need to view the code to press F3.

Why we want to view the source code:
1, look at the source code can understand how others write this technology, let us understand more in-depth.
2. Absorbing Daniel's ideas.

See the source code the most taboo point: not every line of code to understand what the meaning, can see a guess what he means is enough.
*/

/The following examples are mainly intended:
We can also rewrite the method of the object parent class;
You need to add a @override when rewriting;
When you generally override the Equals method of a class, you also override its Hashcode method

Class person{

int id;

String name;

public person (int ID, String name) {
This.id = ID;
THIS.name = name;
}

Public person () {
}

Currently I need to output an object directly, the output format is: No.: 110 Name: Dog Doll this format. The current object
The ToString method does not meet the requirements of subclasses, so we should rewrite the ToString of the object class.
@Override
Public String toString () {
Return "No.:" + this.id + "name:" +this.name;
}


Why to rewrite: The Equals method of object compares the memory address of two objects by default, so I need to compare the ID of two objects, so the Equals method of the object class does not meet my current requirement. 。
@Override
public boolean equals (Object obj) {
Person P = (person) obj;
return this.id== p.id;
}

@Override
public int hashcode () {
return this.id;
}


}

(7). StringBuffer
            StringBuffer get better performance when changing string content
            If you need to change the contents of a string frequently, we recommend using the string buffer Class (StringBuffer)
            StringBuffer: A container for storing characters
            Interview title: What is the default initial capacity when creating an object using the StringBuffer parameterless constructor? If the length is not enough, how many times since growth?
            StringBuffer the underlying is dependent on a character array to store the data, with an initial capacity of 16, and an automatic increase of 1 time times if the length is insufficient.
            has the method of adding and deleting changes and other methods.
            StringBuilder is a simple replacement designed for StringBuffer
          & nbsp Not thread safe in single-threaded performance than StringBuffer high

If our program runs on a single thread, or does not have to take into account thread synchronization issues, we should prioritize the use of the StringBuilder class, and of course, if you want to ensure thread safety, natural non-stringbuffer.
StringBuilder instances are not secure for multiple threads. If such synchronization is required, it is recommended to use StringBuffer.

Get started with Java 04

Related Article

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.