Javaoo Next Book Summary

Source: Internet
Author: User
Tags cdata throwable time in milliseconds

Exception handling

Exception class

There are two direct subclasses of class Throwable:error and exception.

Inheritance of runtimeexception and IOException Exception

Error class objects (errors), generated and discarded by the Java Virtual machine (typically, Java programs do not handle such exceptions);

The Exception class object is an object that is processed or discarded by a Java program.

Only class RuntimeException and its subclasses in the exception class are not run-time exceptions;

The Java compiler requires that a Java program must catch or declare all non-runtime exceptions, but the runtime exception can be handled without processing .

Exception Handling Keywords

Java exception handling is implemented by 5 keywords: try,catch,throw,throws,finally.

Try statements (exceptions may occur)
The Try statement uses curly braces {} to specify a piece of code that might discard one or more exceptions.

Catch statement (handles exception)
The parameters of a catch statement are similar to the declaration of a method, including an exception type and an exception object. The exception type must be a subclass of the Throwable class, which indicates the exception type that the catch statement handles, and the exception object is generated and captured by the runtime system in the code block specified by the try, which contains the processing of the object, where the object's methods can be called.

A catch statement can have more than one exception that handles a different class. The Java Runtime system detects the exception type processed by each catch statement from top to bottom until a matching catch statement of the type is found. Here, a type match means that the exception type handled by the catch is exactly the same as the type of the generated exception object or its parent class, so the order of the catch statement should be from special to generic.

You can also use a catch statement to handle multiple exception types, where the exception type parameter should be the parent of these multiple exception types, and the exception handling type of the catch statement should be selected according to the specific situation in the program design.

Finally statement (concluding sentence)
In the code that is qualified by try, when an exception is discarded, subsequent code is not executed. You can specify a piece of code by using the finally statement. Regardless of whether the exception is discarded or not discarded in the block specified by try, and whether the exception type of the catch statement is consistent with the type of the exception being discarded, the code specified by finally is executed, providing a uniform exit. Cleanup of resources is usually possible in the finally statement. such as closing open files.

Throws statement (declaring exception)
Throws always appears in a function header to indicate the various exceptions that the member function might throw. For most exception subclasses, the Java compiler forces you to declare the type of exception thrown in a member function. If the types of exceptions are error or runtimeexception, or their subclasses, this rule does not work because this is not expected in the normal part of the program. If you want to explicitly throw a runtimeexception, you must declare its type with the throws statement.

Throw statement (throws exception)
The throw always appears in the function body and is used to throw an exception. The program terminates immediately after the throw statement, and the statement following it does not execute

Common classes

System class

Returns the current time in milliseconds

Long Start=system.currenttimemillis ();

Terminating a currently running JVM virtual machine

System.exit (0);

Garbage collection

System.GC ();

String-related classes

String StringBuffer StringBuilder

Difference

String test1= "abc";

StringBuffer test2=new StringBuffer ("abc");

StringBuilder test3=new StringBuilder ("abc");

Date class

Many methods in the date class are obsolete and replaced by calender

Regular expressions

For validating formats

String stu= "ABC";

Pattern pattern=pattern.compily ("validation Rules");

Matcher Matcher=pattern.matcher (STU);

System.out.println (Matcher.matches ());

If the rule is met, Matcher.matches () is true;

Reflection (Runtime explores and uses classes that are not known at compile time)

There are three types of loaders : Root loader extension ClassLoader System class loader

When a class is loaded into the JVM, the same class is not loaded.

Connection

Merge binary into JRE during connection phase

Thread synchronization

Implement Runnable Interface than inherited thread class has the advantage of:

1 ): Suitable for multiple threads of the same program code to process the same resource

2 ): You can avoid Java The limit of single inheritance in

3 ): Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent.

The life cycle of a thread

After the thread is created and started, it undergoes five states, namely new, Ready (Runnable), run (Running), blocking (Blocked), and Death (Dead).

NEW: When a thread is created with the keyword new, it is in a new state, where only the virtual machine allocates memory and initializes member variables, and the program does not execute the thread execution body.

Ready: When the thread object calls the start () method, the thread is in a ready state, and the virtual machine creates a call stack and program counter for it, but at this point the thread is not running, only that the thread can run. Run: When a thread in the ready state obtains the CPU and starts executing the Run method, the thread is running. Blocking: When a thread calls the sleep method, the blocking Io method, the Suspend method, and waits for notification (notify), the thread is nearly blocked. The blocking state will re-enter the ready state at the appropriate time. Death: The thread ends in the following three ways, then it is in the dead state, the Run method executes, the thread throws an uncaught exception, and the direct jump Stop method ends the process. Control of ThreadsIsAlive (): Test thread is active Isdaemo (): Test whether the process is a daemon join (): Wait for the process to terminate sleep (): Let the executing thread hibernate within the specified number of milliseconds, the thread does not lose ownership of any monitor yield () : Pauses the currently executing thread object and executes another thread, which is transferring the thread to the Ready state setpriority (int newpriority): Change the priority of the threadCommunication of ThreadsJava in order to avoid polling detection, through the wait (), the Notify () and the Notifyall () method to implement in-process communication mechanism. Wait (): tells the calling thread to discard the monitor into wait mode until another thread enters the same monitor and calls the Notify () method. Notify (): Wakes up a single thread waiting on this Synchronizer Notifyall (): Wakes up all the threads waiting on this Synchronizer

Java Collection Framework

Set, list, and map can be seen as the three main classes of collections.

The list collection is an ordered collection, and the elements in the collection can be repeated, and accessing the elements in the collection can be accessed based on the index of the element.

The set collection is an unordered collection, and the elements in the collection cannot be duplicated, and access to the elements in the collection can only be accessed based on the element itself (and the reason that the elements in the collection are not allowed to be duplicated).

The map collection holds elements of the key-value pair form, which can only be accessed by the key of each element when accessing its value.

Collection interface:

Set interface:

HashSet specific Class (no order, no duplicate data, can be null)
Linkedhashset Concrete Class
TreeSet Concrete Class
List interface: ArrayList specific class
LinkedList Concrete Class
Vector class vectors specific classes
Stack Concrete Class
Map Interface: HashMap class
Linkedhashmap class
TreeMap class

ArrayList: The method of array is implemented, the query efficiency is high, and the efficiency is low.

LinkedList: By the way of the chain list, adding and deleting the efficiency is high;

Generic type

Pros: 1. Ensure data security

2. Data types do not need to be converted

Map interface (key-value pair, key--value one by one, key cannot be duplicated, value can be duplicated)

Java Image Interface Programming

There are two sets of ATW and swing components in Java to support graphical user interface programming.

ATW is the first to appear, but is too dependent on the operating system, there is a great disadvantage, AWT relies on local methods to achieve its function, so the AWT component is often referred to as heavyweight components.

Swing was developed on top of ATW. Completely Java code written, independent of the operating system, you can adjust the appearance, making programmers more convenient to write programs.

Swing's GUI (graphical user interface) is made up of containers and components, where containers are placed.

Layout Manager

FlowLayout: Components are arranged horizontally from left to right in a row.

BorderLayout: North, South, east, west, middle.

GridLayout: Arranging components in a grid of rows and columns

BoxLayout: More complex, more powerful grid layouts

Event-driven programming

Event: The object that describes what happened.

There are different types of event classes used to describe various types of user interaction.

Event Source : The generator of the event.

Event Handlers : methods to receive events, interpret events, and handle user interaction

JAVA I/O systemClassification of IO streams
    • Divided into: character stream and byte stream according to different types of processing data
    • Divided into: input stream and output stream according to data flow
    • According to the data function is divided into: node flow and processing flow

As long as you are working with plain text data, you prioritize the use of character streams, and in addition, you use byte streams.

byte stream : manipulating flows in bytes

    • InputStream
    • OutputStream

character Stream: manipulating flows in characters

    • Reader
    • Writer

input stream : From the point of view of the program, the stream entered into the program

    • InputStream
    • Reader

output stream : From a procedural point of view, the stream output from the program

    • OutputStream
    • Writer

node Flow : Directly connected to the data source, operation Flow

processing Flow : Direct use of node stream, read and write inconvenient, in order to read and write files faster, with the processing stream. The processing stream does not directly connect to the data source, but instead connects to the existing stream (the node stream or processing stream), providing the program with more powerful processing power by processing the data

Object flow: Transmits data in an object unit. Use the class ObjectInputStream and ObjectOutputStream implementations to save the stream in FileOutputStream and FileInputStream classes.

Serialization of objects: Converts objects in a heap into the form output of binary data.

Deserialization of objects: Restores binary data to objects in piles.

Serialization Flag keyword: Serializable

Keywords that cannot be serialized: transient

Serialization: Only one object is serialized into a byte stream for network transmission or persistence.

Inductive summary

    • Steps to use the flow:

      1. Open an input/output stream object
      2. Reading or writing data
      3. Releasing resources, closing input/output stream objects
    • InputStream and OutputStream are mainly used to deal with numbers that can be read directly as Byte.

    • Reader and writer are mainly used to deal with text

Java Network programming

Network programming is the transfer of data between two or more than two devices, such as a computer. What the programmer is doing is sending the data to the specified location, or receiving the specified data, which is the narrow network programming category. When sending and receiving data, most programming languages design specialized APIs to implement these functions, and programmers only need to invoke them.

The ToString method of the object class is covered in the InetAddress class, and we can know that the ToString method in InetAddress returns the host name and IP address separated by "/". Therefore, by outputting the native computer name and IP address directly through the LocalAddress object in the preceding code (after passing the object parameter to the Println method, the Println method invokes the ToString method of the object parameter to output the result).

Getlocalhost only returns the first IP when the computer is bound to multiple IPs. You can use the Getallbyname method if you want to return all the IP for this machine.

Getbyname () method

This method is the most commonly used method of the InetAddress class. It can obtain the corresponding IP address from DNS by specifying the domain name. Getbyname A string parameter that allows you to specify the domain name of the remote host by using this parameter

TCP Programming

In the Java language, the network programming of TCP is provided with good support, in the actual implementation, the Java.net.Socket class represents the client connection, and the Java.net.ServerSocket class represents the server-side connection.

The most common way to connect a server program through the socket class is to pass the IP or domain name and port number as parameters into the socket class through the socket class's constructor. The constructor of the Socket class has many overloaded forms, the most commonly used form: the public socket (String host, int port). From the definition of this constructor, simply pass in the IP or domain name and port number directly into the constructor function.

Sending and receiving data

The two most important methods in the socket class are getInputStream and Getoutputstream. These two methods are used to obtain the InputStream and OutputStream objects used to read and write data, respectively. Here InputStream reads the data that the server program sends to the client, and OutputStream is the data that the client sends to the service-side program.

Turn off network connections

There are 4 things that can cause network connections to close:

    1. Call the Close method of the socket class directly.
    2. As long as the socket class InputStream and OutputStream have a shutdown, the network connection shuts down automatically (you must close the stream by calling the Close method of InputStream and OutputStream for the network connection to shut down automatically).
    3. The network connection shuts down automatically when the program exits.
    4. The socket object is set to null or not closed most using the new socket (...) After a new object is created, the network connection is automatically closed after the JVM's garbage collector reclaims the memory allocated by the socket object.

Although these 4 methods can achieve the same goal, a robust network program is best to use the 1th or 2nd method to shut down the network connection. This is because the 3rd and 4th methods generally do not close the network connection immediately

Create a ServerSocket object

The ServerSocket class is constructed in four overloaded forms, which are defined as follows:

    1. Public ServerSocket () throws IOException
    2. Public ServerSocket (int port) throws IOException
    3. Public ServerSocket (int port, int backlog) throws IOException
    4. Public ServerSocket (int port, int backlog, inetaddress bindaddr) throws IOException

Parameters: Port is the ServerSocket object to bind to, the backlog is the length of the request queue, BINDADDR is the ServerSocket object to bind the IP address.

The constructor throws a IOException exception when the port specified by the port parameter is already bound. But the exception that is actually thrown is bindexception.

UDP programming

UDP (User Datagram Protocol) is a non-connection protocol used to send binary data from one computer to another computer. Both the sender and the receiver of the datagram packet in Java use the Java.net.DatagramSocket class to send and receive packets.

The Datagramsocket is constructed as follows:

    • Public Datagramsocket () throws SocketException
    • Public Datagramsocket (SocketAddress bindaddr) throws SocketException
    • public datagramsocket (int port) throws SocketException
    • public datagramsocket (int port, inetaddress laddr) throws SocketException

The meaning of each parameter in the constructor: port is bound to the port specified by the local host, BINDADDR is the local socket address that encapsulates the server and port number, and LADDR is the local address to bind.

Common methods:

    • public void Send (Datagrampacket p) throws IOException
    • public void receive (Datagrampacket p) throws IOException

Both of these methods have a datagrampacket parameter. Datagrampacket represents a datagram packet, similar to Datagramsocket, which is used by both the sender and receiver of the package. Datagrampacket has six construction methods, of which two are used by the receiver and four are used by the sender.

To receive a datagram package:

    • Public Datagrampacket (byte[] buf, int length): Used to receive a length of data packet, buf the buffer to hold the incoming datagram.
    • Public Datagrampacket (byte[] buf, int offset, int length): Used to receive the length of the package, offset offsets are specified in the buffer buf.

To send a datagram package:

    • Public Datagrampacket (byte[] buf, int length, inetaddress address, int port)
    • Public Datagrampacket (byte[] buf, int offset, int length, inetaddress address, int port)
    • Public Datagrampacket (byte[] buf, int length, socketaddress address) throws SocketException
    • Public Datagrampacket (byte[] buf, int offset, int length, socketaddress address) throws SocketException

These methods are all sent to the specified port number on the specified host for a length-long package.

Receive Datagram Packets

The following steps are taken to receive a datagram package:

    1. Create a byte array that is large enough to store the data for the datagram packet to be received.
    2. Instantiates a Datagrampacket object with this byte array.
    3. Datagramsocket is instantiated, and it is assigned to a port on the local host to which the socket is bound.
    4. Call the Receive () method of the Datagramsocket class to pass the Datagrampacket object to the method, which will cause the execution thread to block until a datagram packet is received or timed out.

After the Reveive () method returns, the new package has just passed successfully, and if a timeout occurs, the receive () method does not return, but throws an exception. The GetData () method of the Datagrampacket class can be used to receive an array of bytes that contain the datagram packet data.

Sending a datagram packet

To send a datagram package, follow these steps:

    1. Create a byte array that is large enough to store the data for the datagram packet to be sent.
    2. Creates a Datagrampacket object that stores the byte array, along with the name of the server and the port number of the recipient.
    3. Datagramsocket is instantiated, and it is assigned to a port on the local host to which the socket is bound.
    4. Call the Send () method of the Datagramsocket class, pass the Datagrampacket object parameter, and send the datagram packet.

Java Database programming

JDBC is a Java API for executing SQL statements that provides unified access to a variety of relational databases, consisting of a set of classes and interfaces written in the Java language. JDBC provides a benchmark to build more advanced tools and interfaces that enable database developers to write database applications very easily.

DAO Data Access object, which is located between the business logic and persisted data, is the primary function for accessing persisted data.

DAO isolates the business logic code and the data access code, which makes it easy for us to implement the persistence of different databases.

In fact, DAO is a converter-like feature that transforms an entity into a record in a database or converts a record in a database into an entity.

Usually DAO consists of the following four elements:

    • Database Operations Helper Classes: Enabling database operations accessibility, such as getting connections, closing connections, etc.
    • Entity classes: For data passing
    • DAO Interface: Convention DAO functionality
    • DAO interface Implementation class: Specific implementation of DAO function

Connecting to a database

Class.forName ("Com.mysql.jdbc.Driver");

String url= "jdbc:mysql://local host:3306/database name";

String user= "Database user name";

String pwd= "Database user password";

Connection con=drivermanager.getconnection (URL,ROOT,PWD);

Statement ment=con.creatstatement ();

Java XML Parsing technology

XML refers to Extensible Markup Language (extensible Markup Language), which is a markup language that is much like HTML. XML is designed to transmit data, focus on the content of the data, and HTML is designed to display the data, focusing on the appearance of the data. XML doesn't do anything, it's just designed to structure, store, and transfer information.

XML tags are not predefined, we need to define our own tags, so XML is designed to be self-descriptive, and it is the recommended standard for the system.

XML use

In the real world, computer systems and data use incompatible formats to store data. XML data is stored in plain text format, thus providing a software-and hardware-independent approach to data storage. This makes it easier to create data that can be shared by different applications.

One of the most time-consuming challenges for developers is the exchange of data between incompatible systems on the Internet, which can be reduced by exchanging data in XML because of the variety of incompatible applications that are able to read the data in the XML.

XML Structure

XML is a tree structure. A tree is an important nonlinear data structure, visually, it is the structure of data elements (called nodes in a tree) organized by branches, much like the trees in nature.

XML declaration :

<?xml version="1.0" encoding="utf-8"?>

It defines the version of the XML (1.0) and the encoding (UTF-8) character set used.

All XML elements are paired and there is a start tag that must have a close tag.

XML tags are case-sensitive, and label <Letter> is different from tag <letter>.

The XML document must have a root element, and if the tag needs to be nested, it must be nested correctly, and the label opened inside the inner layer must be closed on the inner layer.

XML tags if you need to add an attribute, the attribute value must be quoted.

The syntax for writing comments in XML is very similar to the syntax of HTML, both <!–this is a comment–>.

In XML, spaces are preserved, unlike HTML, where more spaces are eventually merged into one.

XML element Naming conventions :

    • Names can contain letters, numbers, and other characters
    • Names cannot start with numbers or punctuation marks
    • The name cannot begin with the letter XML (or XML, XML, and so on)
    • Name cannot contain spaces
    • You can use any name without a reserved word.
Dtd

The role of a DTD (document type definition) is to define a legitimate building block for an XML document. XML with the correct syntax is called "well-formed" XML, and we can validate that XML is "legitimate" XML through a DTD.

Attention:

CDATA sections cannot contain the string "]]>", nor do they allow nested CDATA sections.

"]]>" that marks the end of a CDATA section cannot contain spaces or line breaks

External document Declaration

If the DTD is outside the XML source file, it should be encapsulated in a DOCTYPE definition by the following syntax:

<!DOCTYPE root-element SYSTEM 外部文件>

Javaoo Next Book Summary

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.