Chapter 2 advanced Java programming

Source: Internet
Author: User

Chapter 2 advanced Java programming
Learning Guide

This chapter introduces some advanced features in Java: Exception Handling, multithreading, stream I/O, and network communication. Each part can be extended into a topic. Readers have learned only a small part in this chapter. However, they can learn some basic concepts and operations to lay the foundation for further study. Exception Handling provides a mechanism to capture and handle errors. multithreading enables multiple sub-tasks of the program to be executed simultaneously. Streaming Io provides a read/write mechanism for input and output; the network communication feature allows Java programs to implement underlying communication through sockets, and uses the extension components provided by Java to implement high-level services.
  Highlights and difficulties of Teaching:
● Basic concepts and models of exception handling, multithreading, stream I/O, and network communication
● Exception capture and handling
● Multi-thread implementation and runnable interface application
● Stream input/output operations, file read/write, and random access
● Socket-based connection-oriented underlying network communication and high-level services
  9.1 Exception Handling
In Java, error capture and handling mechanisms are provided, that is, exception handling mechanisms. When an error occurs during the running of the program, Java allows the program to complete tasks according to the normal path, and throws an object (exception) that encapsulates the error information to its calling program from the method that finds the error, issue a signal that a problem has occurred and exit immediately. Moreover, the program does not continue executing the code that calls this method, instead, the exception handling mechanism starts to search for an exception processor capable of handling such specific errors.
Exception is also called an exception, error, or violation. It is a special running error object and corresponds to a specific running error handling mechanism in Java. Java introduces exception and exception classes.
Exception Handling in Java
Generally, errors can be captured during compilation, but some errors must be solved during runtime, such as Division by 0. These aspects should be taken into account to handle possible exceptions.
Java uses an object-oriented method to handle exceptions. If an exception occurs during running of a method, this method generates an object representing the exception and delivers it to the runtime system, the system looks for code to handle exceptions.
The process of generating an exception object and handing it over to the runtime system is called throw exception. The system finds the method in the call stack of the method until it finds the method that contains the corresponding exception handling. This process is called catch exception.
Throwable and exception
The throwable class is the superclass of all
Errors and exceptions in the Java language.
The exception classes in Java are subclasses of Java. Lang. throwable, and two subclasses are derived: Error and exception. The error system is retained, and the exception is used by the program.
Error: internal errors of the JVM system, resource depletion, etc. applications do not handle error classes.
Exception: Other general programming errors. Exceptions generally refer to exceptions and their subclasses.
Exception also has its own methods and attributes. It has two constructor methods:
Public exception ();
Public exception (string S );
S is generally a description of the error corresponding to this exception.
The exception class also inherits the methods of the parent class, which are commonly used:
Public String tostring (); returns the string that describes the information of the current exception class.
Public void printstacktrace (); prints the stack usage track of the current exception object on the current output, that is, the objects and classes that the program uses to execute, which causes exceptions.
System-defined exceptions:
Exception subclasses include runtimeexception and non-runtimeexception.
The former is a design and implementation problem, such as array out-of-bounds. This exception can be avoided through programming.
The latter is an exception caused by the environment during the program running.
User-defined exceptions
This type of exception is a class derived from an exception or its subclass. It is used to handle exceptions related to a specific application.
Exception Handling
Capture and Process
Exception Handling Mechanism:
1. if an exception occurs during program execution, an exception class object is automatically generated. The running of the object submitted to Java is a system. This process is called throwing an exception and can also be forcibly executed by the program.
2. When the system receives an exception object, it looks for the code to handle the exception and submits the current exception object to it for processing. This process is called exception capture.
3. If the system cannot find a method to capture exceptions, the system will terminate and the program will exit.
Exception Handling
Throw an exception
All system-defined running exceptions can be automatically thrown by the system.
User-defined exceptions cannot be automatically thrown by the system. The throw statement must be used to define the situation where an exception is generated and an object of this exception class should be thrown.
Throw exception object;
Note: 1. Throw statements are generally defined as executed when certain conditions are met. For example, place it in the IF branch.
2. When using a throw statement or calling methods thrown by exceptions in other classes, you should add a list of throws exception class names in the method header definition.
Capture exceptions
When an exception is thrown, a special statement should be used to receive the exception object. After an exception class object is captured, the program jumps to a special exception handling statement block, or directly jumps out of the current program and JVM.
Exception objects are not active and exceptions are handled by Catch Block (Exception Processing block.
Try {
......
}
Catch (exception class name exception parameter name ){
......
}
Catch (exception class name exception parameter name ){
......
} Finally {
......
}
One or more catch statements are followed by the try block. Each catch must have a try.
Handling of multiple exceptions:
In practical applications, a try block may produce a variety of exceptions. If you want to use different methods to handle these exceptions, you need to use multiple exception handling mechanisms.
Multi-exception handling is implemented by defining several catch blocks after a try block. When a try throws an exception, the program first redirects to the first catch to check whether the exception can be received.
When an exception is received, the exception object matches the catch parameter:
1. Exception objects and parameters belong to the same exception class
2. The exception object is a subclass of the parameter exception class.
3. The exception object implements the interface defined by the Parameter
If the block is received by the first catch, the program executes the block directly and then exits the current method. The statements not executed in the try block and other catch blocks are ignored. Otherwise, match other catch blocks at a time until a Catch Block that can receive the exception object is found.
If none of the catch operations match, the program returns the upper-layer method that calls the method. If the upper-layer method defines a Catch Block that matches the exception, it will jump to the Catch Block. Otherwise, the system will continue tracing. If no program is found, the system will terminate the program and print
Exception information.
If no exception occurs, all catch blocks will be ignored.
Design catch
Because catch blocks are executed sequentially, catch blocks that handle more specific and Common exceptions are generally placed in front, catch blocks Matching Multiple exceptions are placed at the back of the Catch Block.

The Catch Block performs different operations based on different exceptions. Generally, the exception and error information is printed to facilitate the modification of the debugging program.
Finally
The finally statement provides a unified interface for exception handling. That is to say, whether an exception occurs or not, the program must execute a piece of code, so the code is placed in the finally statement block.
The finally statement is optional. Try must have at least one catch or finally block.
Exception Handling
An exception is declared in the override method.
If a throw exception is declared in a class method, its subclass can throw an exception if it is to overwrite the method of the class.
However, you must note that the exception thrown by the subclass method can only be the same type or subclass of the exception thrown by the parent class method, and cannot throw more general exceptions than the parent class.
Exception Handling
Import java. Io .*;
Class {
Public void methoda () throws ioexception
{......}
}
Class B1 extends {
Public void methoda () throws filenotfoundexception
{......}
}
Class B2 extends {
Public void methoda () throws exception // Error
{......}
}
Throw exception supplement
Sometimes, throw is required if the exception defined by the user program cannot be automatically thrown by the system. For example, if you want the try code to generate an exception, throw the exception.
One is to handle exceptions by yourself in the method, and the other is to handle exceptions outside the method.
Create your own exception class:
Although many existing exceptions exist in the Java software package, in actual programming, you also need to set up your own exception classes to handle specific running errors of an application.
To create a user-defined exception, complete the following steps:
1. Declare a new exception class, which must inherit the existing exception class of the system.
2. Define attributes and methods for the new exception class, or reload the methods of the parent class so that these attributes and methods can reflect the error information corresponding to the class.

 

  9.2 Java multithreading mechanism
Create thread: place the subtask code that needs to be run independently into the run method of the class derived from the Thread class. Then, create an instance of the thread class where the subtask was originally called in the main thread, and then call the start method in the Thread class to start the thread.
The preceding section describes how to create a Thread class to implement multithreading, namely separating the Thread class from the main class of the program.
Class countersubtask extends thread
{...
Public void run ()
{...}
}
Public class countermultithread
{Public static void main (string [] ARGs)
{...}
}
If the countersubtask class, that is, the class where the run method is located already has another superclass, it will not be able to inherit the Thread class. How can we implement multithreading at this time? Typically, a GUI program needs to be derived from a jframe or japplet class. At this time, although the Thread class cannot be inherited, You can implement multiple threads by implementing the runnable interface.
  9.3 Stream Input/Output and File Processing
In Java, the data to be read and written by an application is implemented through I/O operations. The source or destination of the read/write data includes files, memory, and network connections. Among them, files are most commonly used.
The input and output streams in Java can be divided into two categories: Input streams and output streams. An input stream is an object that can read bytes, and an output stream is an object that can write a byte sequence. The originally designed input and output class is oriented to byte streams, that is, it supports eight-bit byte streams, which are represented by class levels derived from the abstract classes inputstream and outputstream. However, with the demand for international support, byte-oriented streams cannot well process Unicode (two bytes for each character) data, therefore, the class hierarchy derived from the abstract class reader and writer is introduced for reading and writing double-byte Unicode characters, rather than single-byte characters.

 

9.3.1 inheritance relationship of JAVA input/output class library
9.3.2 Io operations based on standard input and output
In Java, "standard input stream" and "standard error output stream" are also provided, which correspond to system. In And system. Err respectively. System. Out and system. Err have been encapsulated into printstream objects, so they have powerful output functions. However, system. In is still the original inputstream and needs to be encapsulated during use.
9.3.3 file read/write and Random Access
A file is the data stored on a secondary storage device such as a disk. It is composed of records. A row in the file can be considered as a record. The reading and writing of files is very similar to that of standard input and output. It is important to note that the stream for file operations should be used and the stream should be closed when appropriate, otherwise, system resources cannot be released. If the output stream is not closed, the data in the buffer may not be written to the file, resulting in file corruption.
9.3.4 Java File Management
For other operations on files or directories, such as renaming, deleting, and listing, you must use the file management class of Java.
In Java, both files and directories are represented by file objects. Creation and differentiation methods: create a file object and specify the file name or directory name, if the specified file name or directory name does not exist, the creation of the file object will not create a file or directory. You need to use the createnewfile method or mkdir method to create a file or directory respectively. To identify whether a file object represents a file or a directory, you can use the isfile method and isdirectory method to determine whether the object represents a file or a directory.
  9.4 Java Network Communication
Traditional network programming is a very detailed task. programmers must deal with a large number of network-related details, such as various protocols, and even understand network-related hardware knowledge. Java shields the underlying network communication details so that the programming model used is a file model, that is, network data transmission can be operated like an operational stream. In addition, in network connection, a server is usually required to serve multiple clients at the same time, So Java's multithreading mechanism is also useful.

 

9.4.1 basic network knowledge and Java Network Model
9.4.2 connectionless Datagram
For applications with more important transmission speeds, use the connectionless Datagram Protocol UDP, that is, the "User Datagram Protocol ". UDP does not deliberately pursue that data packets will be completely sent out, nor can it guarantee that they will arrive in the same order as when they are sent. Therefore, this is an "unreliable protocol ". Because it is much faster than TCP, it can still be used in many applications.
Java's support for datagram is roughly the same as its support for TCP sockets. The datagramsocket class is used to represent a connectionless socket and receive and send a datagram. The content of the received and sent datagram is stored in the datagrampacket object.
UDP also has its own port, which is independent of the TCP port. That is to say, you can run a TCP and UDP Service Program at the same time on port 8080 without conflict between the two.
9.4.3 Java access to network resources
Many services have been developed on the Internet, such as WWW browsing and email. Java also provides corresponding extension components, such as javamail APIs for email applications, you only need to call the provided method to complete the mail sending operation:
Transport. Send (Message );
On the Internet, we use the generic Resource Locator URL (Uniform Resource Locator) to find resources. A URL contains information used to find a resource, such as an image or a file. There are many types of URL resources, such as HTTP resources and FTP resources. The following is the URL of an image resource, which belongs to an HTTP resource.
Summary of this Chapter
This chapter describes the basic concepts and models of Java Exception Handling, multithreading, stream I/O, and network communication.
In exception handling, the advanced error correction and recovery mechanisms provided by Java can effectively enhance the code robustness, use as much streamlined code as possible to create large and reliable applications, and eliminate uncontrollable errors in the program. Java forces compliance with all aspects of the violation, so both the library designer and the customer programmer can use it continuously and consistently.
The main purpose of multithreading mechanism is to manage a large number of tasks in an orderly manner, so that you can use computer resources more effectively through "mild" switching, or use the interface more friendly for users, compared with the "severe" switching between processes, the efficiency is greatly improved. A typical application of effectively utilizing computer resources is how to use the CPU during I/O wait; A typical user interface friendliness is how to respond to the "stop" operation quickly during a long period of data download.
In Stream Input and Output, Java provides stream libraries that can be accessed in different ways through different data sources or purposes, such as the console, files, memory blocks, and even the Internet. Flexible I/O operations are provided through the correct use of the flow filter. Java not only provides stream access to files, but also provides random access and file management.
In network communication, Java not only provides underlying communication for connection and connectionless datagram, but also provides high-level services such as email and WWW services. Through the network functions provided by Java, network data can be transmitted in a stream mode, and you do not need to pay attention to the details of the network connection.

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.