Java Basic concepts (not finished)

Source: Internet
Author: User
Tags bitwise bitwise operators logical operators object serialization wrapper

Simple Summary ~ Secondary quick Recall ~

First, Jvm1,java class loading mechanism

The Java program consists of multiple class files, which are loaded on demand.

The dynamic extension of Java is implemented by dynamic loading and dynamic linking at run time. -Dynamic binding, polymorphic.

Loading steps:

1) Load: Find and Import class files.

A) obtain a binary byte stream based on the fully qualified name of a class

b) Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.

c) In the Java heap, generate a class object that represents it as the access entry for the method area data.

2) Link: Merges the binary data of the class into the JRE.

a) Verify that the class file is checked for correctness

b) Prepare : Allocate storage space for static variables of class

The class variable is formally assigned and set the class variable initial value, which is allocated in the method area. The initial value refers to a value of 0.

Note that only the static class variable is included in the memory allocation at this time, not the instance variable. Instance variables are assigned to the heap along with the objects.

c) Parsing : Turning a symbolic reference into a direct reference

3) Initialization: Initializes the static variables and static code blocks of the class.

A) Timing: Use the new keyword to instantiate an object, read or set a static field for a class (except that the final constant has been placed outside the constant pool at compile time), and invoke a static method.

b) Reflection: If the class is not initialized, its initialization is triggered first.

c) Initialize the subclass: Initializes the parent class if it discovers that its parent class is not initialized.

d) Virtual machine Startup: First initialize the user-specified main class, which contains the class of main ().

It is particularly important to note that when you invoke a static field of a parent class through a subclass, only the parent class is initialized, and the subclass has nothing to do with =,=, because this field is not his own static field.

A reference to a constant is actually converted into a reference to the constant pool of the class itself, and it has nothing to do with class initialization =,=

2, class loader ClassLoader

The class loader, looking for a class of bytecode files, constructs an object that represents the class within the JVM.

(1) ClassLoader and parental assignment model

Look for the JRE directory, look for Jvm.dll, initialize the JVM.

Generates a bootstrap ClassLoader, automatically loads extension ClassLoader, and sets its parent loader to bootstrap ClassLoader.

Bootstraploader automatically loads the app ClassLoader, setting its parent loader to extension ClassLoader.

Bootstrap ClassLoader: Loading a class library in the <java_home>\lib directory, identified by file name, does not load even if placed in the directory. The loader cannot be referenced directly by a Java program.

Extension ClassLoader: Loads all class libraries under the extended Api,<java_home>\lib\ext directory.

Appclassloader: Loads custom classes on the user's machine, classpath directory.

"Delegating model Work Process"

If a class loader receives a request for a class load, it first delegates the request to his parent ClassLoader, which is the case for each level of the ClassLoader, so all load requests should be routed to the top-level startup class loader. The child loader tries to load itself only when the parent loader has feedback that it cannot complete the load request (it does not find the desired class in the search scope).

Benefits

1. There is a hierarchical relationship of precedence between class loaders. The parent loader takes precedence to ensure that the core API is loaded correctly and improves security.

2. Avoid repeated loading, classes that the parent class has already loaded, and subclasses that do not need to be loaded.

"LoadClass's main code"

(2) How to distinguish the loading method of Class forname ()

The static methods of LoadClass () and class in ClassLoader forname () are used to load classes.

The general usage is:

Class clazz = class.forname ("name");

Or:

ClassLoader loader = Thread.CurrentThread (). Getcontextclassloader ();

Class clazz = Loader.loadclass ("name");

Note that when loading a class with the ClassLoader, only the class name is passed in, without the initialization flag resolve, and the second parameter defaults to False, which means that the class is not interpreted or initialized, and simply loaded.

Class.forName also only passes in the class name, but it is initialized by default, and the class is interpreted and initialized.

3. JVM character encoding and IO

The characters inside the JVM have only one form: UNICODE. The encoding conversion occurs only at the junction of the JVM and the OS, the IO stream.

Inside the JVM, character unification is expressed in Unicode, but when it needs to be output to the outside of the JVM, it uses the encoding conversion, which is the specific character.

(1) IO Stream and encoding conversion

Divided into two major camps: character-oriented and byte-oriented.

Byte-oriented: The binary content in the file is consistent with what is read inside the JVM. You cannot change any 01 order. This input and output is suitable for reading into audio, video files, or files that do not require any transformations.

Character-oriented: the characters in the file are consistent with those that are read into the JVM. Therefore, the character-oriented IO class implicitly does the encoding conversion. When you enter, the characters in the file are converted to Unicode characters, and the output is encoded as characters.

Note that the encoding conversion scheme can only be used by default, if you need to specify a conversion encoding, only where the byte stream is converted, that is, InputStreamReader and OutputStreamWriter.

(2) Adorner mode

Adorner mode allows you to add new functionality to an existing object without changing the original structure.

Requires that the adorner must have the same interface as the decorated object.

InputStream abstract class defines the abstract method read (). One of its subclasses is FilterInputStream, which is the centerpiece of the adorner class.

The FilterInputStream class internally maintains a member object of the InputStream class, and all of its methods are called methods with the same name as the class. Therefore, this class only acts as a delegate.

However, its subclasses are adorner classes and can provide a variety of different functions. For example, the Bufferedinputstream provides buffering capabilities. In its read () method, detects whether the current position pos exceeds the buffer size, and if so, calls fill () to output the buffer contents.

Entity flow connects directly to the stream of the data source. can be used alone.

such as Fileinputstream,fileinputstreamreader, Fileoutputstream,fileoutputstreamreader.

The decorative flow does not directly connect to the data source, but is based on the entity flow object or the decorative flow object, enhancing the read and write ability of the entity stream. Cannot be used alone, flow nesting is required.

such as Bufferedinputstream, Bufferedoutputstream, BufferedReader, BufferedWriter.

The bridge stream byte stream is converted to a character stream

When a decorative stream is nested, only the same type of flow can be nested. InputStream and reader are two different systems. A bridging stream is required for conversion. such as the InputStreamReader and Outputstreamreader classes.

(3) Diagram of IO class

Second, the grammatical details 1. Self-increment self-subtraction operation

Pay attention to the difference in the first increment and then the value of the case.

intermediate variable caching mechanism

This involves the mechanism of intermediate cache variables in Java. Equivalent to: Tmp=j, J=j+1, j=tmp. So after the expression is finished, j=j, it will not change.

2. Data type Conversion

Java basic data types fall into three main categories: Boolean, character, numeric. The numerical type is also divided into floating-point and integral type.

8 Basic types: Boolean, char, Byte, short, int, long, float, double.

Corresponding wrapper classes: Boolean,character, Byte, short, Integer, Long, Float, Double.

In addition, the more commonly used classes are string and date.

Java basic data types are platform independent, fixed bytes: Boolean not specified, Byte-1, char-2, Short-2, int-4, Long-8, float-4, double--8

(1) Conversions between basic data types

From low to advanced can be automatically converted, from high to low need to force type conversion. There is also a need for strong transfers between peers, such as Char,byte,short.

From low to High: (Byte, short, char)-int-long-float-double

Forcing type conversions can result in overflow or decreased precision.

(2) Type conversion function provided by the wrapper class

When converting between basic data types, you can take advantage of wrapper classes as intermediate transitions. The type conversions are then made using the methods provided by the wrapper class.

The general wrapper class provides such functions as: Doublevalue (), Intvalue (),.... toString ().

(3) Convert character variable to numeric type

One is that char corresponds directly to the ASCII code.

The other is the conversion of mathematical meanings, character provides the getnumericvalue (CHAR-ch) method.

3. Assert assert ()

When the Boolean expression is False, a assertionerror is generated. For debugging purposes.

You can place assertions at any location that you expect to not arrive normally.

Assertions should not change the state of the program in any way.

4. Operator (1) Type promotion

In an operation, if there are low-level and advanced basic data types in the expression, the lower level is automatically promoted to advanced. Do not forget this!

(2) Constant type

If a constant occurs in an expression, the type of the operation is the type of the very amount. For example, if one expression is constant 10 and the other is type T, the output is type T.

(3) Boolean logical operators

Bitwise Operators & | ^

Logical Operators && | |

Boolean logical operators: When an operand is a Boolean type, the bitwise operator can be used as a Boolean logical operator.

Boolean logical operators have higher precedence than logical operators , and the important difference is that boolean logical operators are non-short-circuiting , and logical operators are optimized and short-circuited.

In the above example, because the logical operator is short-circuited, the first expression is false and the second is not executed. But the Boolean logical operator is silly, it will certainly execute two expressions, only give the final result, so n++ was executed once.

Third, abnormal system

Java's only formal reporting mechanism for errors. Enforced by the compiler.

Separation of normal code and exception handling code, the structure is clear and concise.

Think of everything as a transaction, guarded by exceptions.

Can be seen as a built-in recovery system. Multiple recovery points.

1. The process of throwing exceptions

First, create an exception object on the heap with the new keyword.

The current path is terminated, and a reference to the exception object pops up.

Taken over by an exception handler, recovered from the error, either continuing or running in another way.

2. The difference between throw and return

In a sense, throw is a special kind of return mechanism. It's just different from the return point of the normal return.

The location where the exception is returned is the exception handler, which may be far from the place where the exception was thrown, even across multiple layers of the method call stack. and return returns only one layer.

3. Java Standard Exceptions

Root class Throwable.

Two types: Error and exception.

Error indicates compile-time and system errors, typically thrown by the JVM.

Exception is an exception in the application. It is generally divided into exceptions that are subject to check and unchecked.

RuntimeException is the only exception that is not checked. Automatically thrown by the JVM, usually without capture, represents a programming error, and the programmer should check the code.

The opposite is the checked exception, which is not allowed to be ignored in code and enforced by the compiler.

"A common runtimeexception"

Bufferoverflowexception

ClassCastException

Concurrentmodificationexception

Emptystackexception

IllegalArgumentException

Indexoutofboundsexception

NullPointerException

SystemException

4. Keywords

Try-catch-finally cannot be used alone. The scope of the variables in the three code blocks is within the code block and cannot be accessed from each other, and if you want to access them in three blocks, you should define the variables outside the block.

If there are multiple catch blocks, match them sequentially, matching only one exception.

The Throw keyword is used inside the method body to throw an exception. If an exception is thrown within a method, you should also declare the possible exception in the method header with throws.

The caller of the method should handle the exception except for error and runtimeexception.

Four, the difference: final, finally, Finalize1. Final

Used to decorate members, methods, method parameters, classes.

(1) Final member

Once a member variable is initialized, its value is no longer changed. If it is a reference, the reference cannot be changed, but the field of the object to which the reference refers can be changed.

Initialization can be in two locations: one is defined, and the other is the constructor function.

(2) Final parameter

Note that function arguments are passed by value. When final is added, it means that the parameter is not allowed to be modified inside the method.

For basic type variables, there is no effect, because the base type itself is passed by value, and the internal modification inherently affects the original parameter.

However, for reference-type variables, you cannot modify the object you are pointing to in a method, preventing accidental modification.

(3) Final method

Two meanings:

1) Overwrite and inheritance are not allowed. can be overloaded.

2) allows the compiler to convert all calls to this method into an inline invocation mechanism. When the method is called, the method body is inserted directly at the call. Eliminate routine method calls, such as saving breakpoints, pressing stacks, and so on.

Note that while the inline invocation mechanism may improve the efficiency of the program, the calling body code expands rapidly in the case of multiple calls to the method, which can affect efficiency. Use the final method with caution.

(4) Final class

Inheritance is not allowed and is a leaf class in the inheritance tree. All methods are final by default.

This contradicts the abstract, so a class cannot be modified by both final and abstract.

2. Finally

is the best complement to the exception handling model.

The finally structure makes the code always executed, whether or not an exception occurs. Even if there is a return statement in the try block, finally will certainly be executed before the return.

Typically used to maintain object state and clean up non-memory resources.

3. Finalize ()

is an object method related to JVM garbage collection. This method may be called when the garbage collector prepares to reclaim an object.

Usually used for some of the release of resources that are not easy to control and very important, for example, some IO operations, data connections.

Note that in the application, you should not just rely on finalize to release resources, but through the program itself to manage the resource-based, finalize function release resources supplemented by the double insurance Management mechanism. Because the JVM does not guarantee that the function will be called, even if the call is called only once.

V. Reflection

The concept of reflection is not unique to Java. Objective-c supports reflection, but C + + does not support it.

Allows the running program to check itself and to manipulate the internal properties of the program directly.

The dynamic proxy provided by the reflection API is a very powerful feature that can natively implement the method interception functionality in AOP.

The advantage is that flexibility is strong. The disadvantage is that performance is relatively poor. For the same operation, the time required to use the reflection API is approximately one or two orders of magnitude slower than the direct one.

Therefore, it is necessary to weigh flexibility and performance when using reflection.

1. Get the internal structure of the runtime

Once you have taken a class object, you can traverse the constructor of a Java class, the declared domain, and the defined method.

The corresponding methods were GetConstructor, GetField, GetMethod. --only the public method can be obtained.

There are corresponding Getdeclaredconstructor, Getdeclaredfield, Getdeclaredmethod. --can be obtained to all methods, including protected, private.

2. Run-time operation of a Java object

Dynamically creates an object of a class that takes a value of a field and invokes a method.

Note that after obtaining the internal structure of the class, you can bypass the Java default access control check by fetching the method object, the constructor object, and the Field object, calling Setaccessible (true) . This gives you access to the private methods, constructors, and domains.

VI. dynamic agent mechanism 1. Proxy mode

Provides a proxy that controls access to an object (hiding and securing the delegate Class). The proxy class is responsible for preprocessing the message for the delegate class, filtering the message and forwarding the message, and performing the processing after the message is delegated to the class.

To keep the behavior consistent, the proxy object and the Proxied object generally implement the same interface, and the caller interacts with the proxy object.

The presence of the agent is transparent to the caller, and the caller sees the interface.

Proxy objects can encapsulate some internal processing logic, such as access control, remote communication, logging, caching, and so on.

This pattern has been widely used in RMI and EJB.

2. Dynamic agent mechanism of JDK5

At run time, you can dynamically create a proxy class that implements multiple interfaces. The object for each proxy class is associated with an Invocationhandler interface implementation that represents the internal processing logic.

When the user invokes a method in the interface of the proxy object, the message of the call is passed to the Invocationhandler invoke method. In the parameters of the Invoke method, you can get to the proxy object, the method object corresponding to the methods, and the actual parameters of the call. The return value of the Invoke method is returned to the consumer.

This practice is actually tantamount to intercepting method calls.

"Main class: Java.lang.reflect.Proxy" provides a set of static methods to dynamically generate a proxy class and its objects for a set of interfaces.

"Processor interface: Java.lang.reflect.InvocationHandler" Defines an Invoke method that centralizes the method invocation on the dynamic proxy class object.

The first argument is the proxy class instance, the second parameter is the method object being called, and the third is the calling parameter.

Each time a dynamic proxy class object is generated, you need to specify a calling processor object that implements the interface, specifying a class loader.

The dynamic proxy class generated by the proxy static method also needs to be loaded through the class loader to be used, and the only difference from the normal class is that its bytecode is generated dynamically by the JVM at runtime and does not pre-exist. class file.

"creation process for dynamic agents"

1) Implement the Invocationhandler interface and create your own calling processor.

2) Specify a ClassLoader object for the proxy class, and a set of interface to create the dynamic proxy class.

3) The constructor of the dynamic proxy class is obtained through the reflection mechanism, and the unique parameter type is the calling processor interface type.

4) Create a dynamic proxy class instance through a constructor that constructs a call to the processor object as a parameter is passed in.

"Creating dynamic agents in real-world applications"

The static method Newproxyinstance in the proxy class has encapsulated the procedure 2 through 4, so it can be simplified when used.

3. Spring AOP

Two proxy mechanisms are used: The dynamic proxy of the JDK (interface-based), the dynamic proxy of the Cglib (class-based).

To learn and summarize.

Vii. passing and quoting

Both the pass-through value and the reference are copies of the passed parameters.

It is particularly important to note that the string type is also an object type variable, so it must be a reference copy. Just not a string is a final class, so there is no difference between passing a value and passing a reference.

Eight, input and output stream 1. Randomaccessfile class

Supports read and write to random access files.

Random access to a file behaves like a large byte array stored in the file system.

There is a cursor to the implied array-the file pointer; The input operation reads the bytes from the file pointer, and moves the pointer forward as it reads. The output operation starts writing bytes from the file pointer and moves the pointer forward as it is written. The file pointer can be read by the Getfilepointer method and set by the Seek method.

In addition to implementing the Datainput and DataOutput interfaces, This class has no relation to the stream, reader inheritance system .

The Randomaccessfile class does not support decorations . Must be assumed to have been properly buffered.

Essentially, working in a way similar to combining DataInputStream and DataOutputStream.

Only Randomaccessfile supports the search method and applies only to files.

In java1.4,most of the functionality of Randomaccessfile is superseded by the NIO storage mapping file.

2. A simple read-write file code

2. Serialization

Converts an object that implements the serializable interface into a sequence of bytes.

Lightweight persistence. Persistence means that the life cycle does not depend on whether the program is executing. Lightweight because it is not possible to simply define an object with some kind of persistent keyword, allowing the system to automatically maintain other detail issues. An object must be explicitly serialized and deserialized in the program.

The concept of object serialization is added to the language to support two main features: The RMI, the remote method invocation. The second is the support of JavaBean.

The serializable interface is a markup interface and does not contain any methods.

To serialize an object, first create some OutputStream objects, such as FileOutputStream, to encapsulate them within a objectoutputstream object. Simply call WriteObject (obj) to serialize the object.

When deserializing, only InputStream is encapsulated within ObjectInputStream, and calling ReadObject () can get an object reference, which is transformed down to the specific situation.

Object serialization not only preserves the panorama of an object, but also tracks all references contained within the object and saves those objects. --Deep Copy object net.

Java Basic concepts (not finished)

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.