(this post reproduced from http://www.cnblogs.com/BYRans/) \

Download link for PDF version: Summary of Java Basics.

Java Overview:

1, JDK: Java Development Kit, Java Development and runtime environment, Java Development tools and JRE.

Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE) : Java Runtime Environment (JRE)

3, configure environment variables: let the Java JDK \bin directory tool, can run in any directory, the reason is, the tool directory told the system, when using the tool, by the system to help us to find the specified directory.

Configuration of environment variables:

1) : permanent configuration: JAVA_HOME=% installation path %\Java\ JDK

     path=%JAVA_HOME%\bin

2) : temporary configuration: set path=%path%; C:\Program Files\Java\jdk\bin

Features: By default, the system searches for the program to be executed in the current path. If the program does not exist, the system searches for the program in the specified path.

Classpath configuration:

1) : permanent configuration mode: classpath=. c:\; e:\

2) : set classpath=.; c:\; e:\

 

Note: Something to be aware of when defining the CLASSPath environment variable

If the environment variable classpath is not defined, Java starts the JVM and looks for the class file to run in the current directory.

If classpath is specified, the class file to run will be looked up in the specified directory.

Do you still look in the current directory? There are two cases:

    

What is CLASSPATH? What does it do?

It is an environment variable of the JavAC compiler. Its role is related to the import, package keywords. When you write improt java.util.*, the compiler, faced with the import keyword, knows you’re importing classes from the java.util package; But how does the compiler know where you put the package? So you first have to tell the compiler where the package is; How do I tell it? If java.util package is in c:/ JDK /, you need to put c:/ JDK/in your CLASSPATH. When faced with the import java.util.* statement, the compiler looks for the directory specified by CLASSPATH, looks for subdirectories Java /util, and then finds compiled files (.class files) with names that match. If not found, an error will be reported! CLASSPATH is a bit like INCLUDE paths in c/ C ++ compilers, isn’t it? How does the C/C ++ compiler work when it encounters statements like include? Oh, it’s the same thing! Search INCLUDE paths to view files! When you develop a package yourself and then want to use classes from that package; Naturally, you have to put the package in your CLASSPATH as well! Setting up CLASSPATH can be tricky for JAVA beginners. So Sun made the JDK for JAVA2 a little smarter. You’ll find that after you install, you can still compile basic JAVA programs and execute them without setting CLASSPATH at all.

 

PATH environment variable

PATH environment variable. When a Java program is compiled by executing a command such as javac on the command line, it will search the PATH specified by the PATH variable to see if the corresponding command program can be found. We need to add the bin directory in the JDK installation directory to the existing PATH variable. The bin directory contains frequently used executable files such as javac/ Java /javadoc, etc. After setting the PATH variable, we can execute javac/ Java and other tools in any directory.

 

What do javac commands and Java commands do?

Remember that Java has two parts: one is to compile and one is to run.

Javac: Is responsible for compilation. When javac is executed, the Java compiler program is launched. Compiles a. Java file with the specified extension. Bytecode files that the JVM can recognize are generated. This is the class file, which is the Java runtime.

Java: The part responsible for running. The JVM is started. The libraries required by the runtime are loaded and executed against the class file.

For a file to be executed, there must be a starting point for execution, and that starting point is the main function.

 

Ii. Java Syntax basics:

 

  1. Identifier:

1), numbers cannot begin.

2), do not use keywords.

 

  1. Scope and lifetime of variables:

    Scope of variables:

    The scope starts at the location of the variable definition and ends at the pair of braces in which the variable resides.

    Life cycle:

    A variable is alive in memory from its defined location;

    A variable is lost in memory when it reaches its scope;

     

  2. Data type:

1) : Basic data types: byte, short, int, long, float, double, char, Boolean

A simple type boolean  byte  char  short  int long float  double  void 
Binary digit 16  16  32  64  32  64  — 
Wrapper classes Boolean  Byte  Character  Short  Integer  Long  Float  Double  Void 

 

  1. Operation symbol:

4) Logical operators.

        & | ^ ! && ||

Logical operators except! All are used to join two Boolean expressions.

&: The result is true if both sides are true. Otherwise false.

| : as long as both sides to false result is false, otherwise it is true

^: different from or slightly different from.

If it’s the same, it’s false.

If the result is different, it is true.

The difference between & and && : & : Whatever the left side results in, the right side is involved in the operation.

&&: short circuit and, if the left side is false, then the right side does not argument and operation.

| and | | difference: | : operation on both sides.

| | : short circuit or, if the left is true, then the right not to participate in the operation.

5) Bitwise operators: operators used to operate on binary bits.

        & | ^

<< >> >>>(unsigned right shift)

Exercise: Interchange data between two variables. No third party variables are required.

int a = 3,b = 5; –>b = 3,a = 5;

Method one:

            a = a + b;  a = 8;

            b = a – b;  b = 3;

            a = a – b;  a = 5;

Method 2:

            a = a ^ b; //

            b = a ^ b; //b = a ^ b ^ b = a

            a = a ^ b; //a = a ^ b ^ a = b;

Exercise: efficiently calculate 2*8 = 2<<3;

 

Overloading is defined as: if two or more functions with the same name appear in a class, the function is overloaded as long as the number of arguments or the types of arguments are different.

How to distinguish overloading: When a function has the same name, just look at the argument list. It doesn’t matter what the return value type is.

Overwrite: Polymorphism between parent and subclass, redefining the function of the parent class. If we define a method in a subclass that has the same name and parameters as its parent, we say that method is Overriding.

 

  1. Java Memory Management

    Java memory Management: Drill down into the Java memory area

****Java and C++ have a high wall of dynamic memory allocation and garbage collection. People on the outside want to get in, but people on the inside want to get out.

  1. Summary:

For developers engaged in THE development of C and C++ programs, in the field of memory management, they are the emperor with the highest power, but also engaged in the most basic work of the working people – both have the “ownership” of each object, and shoulder the responsibility for the maintenance of each object from the beginning to the end of life.

For Java programmers, with the virtual machine’s automatic memory management mechanism eliminating the need to write the paired DELETE /free code for every new operation, and making it less prone to memory leaks and spills, everything seems fine with the virtual machine managing memory. However, because Java programmers have entrusted memory control to the Java virtual machine, it can be a very difficult task to troubleshoot memory leaks and spills without understanding how the virtual machine is using memory.

  1. Runtime data area

During the execution of Java programs, the Java VIRTUAL machine divides the memory it manages into different data areas. Each of these regions has its own purpose and time of creation and destruction. Some regions exist with the start of a virtual machine process, while others are created and destroyed depending on the start and end of a user thread. According to the Java Virtual Machine Specification (Version 2), the memory managed by the Java Virtual Machine will include the following run-time data areas, as shown in the figure below:

          

  1. Program counter

The Program Counter Register is a small memory space that acts as a line number indicator of the bytecode being executed by the current thread. In the concept of virtual machine model (just the conceptual model, all kinds of virtual machine may be through some of the more efficient way to achieve), bytecode interpreter to work is by changing the counter value to select a need to be performed under the bytecode instruction, branches, loops, jumps, exception handling, thread to restore the basic function such as all need to rely on the counter. Because multithreading in the Java VIRTUAL machine is implemented by the way threads alternate and allocate processor execution time, at any given moment, one processor (or kernel for multi-core processors) will execute instructions in only one thread. Therefore, in order for a thread to switch back to the correct execution position, each thread needs to have an independent program counter. Counters between threads do not affect each other and are stored independently. We call this type of memory area “thread private” memory. If the thread is executing a Java method, this counter records the address of the virtual machine bytecode instruction being executed. If the Natvie method is being executed, this counter value is null (Undefined). This memory region is the only one where the Java Virtual Machine specification does not specify any OutOfMemoryError cases.

  1. Java virtual machine stack

Like program counters, the Java Virtual Machine Stack is thread-private and has the same lifetime as a thread. Virtual machine Stack describes the memory model of Java method execution: each method execution creates a Stack Frame to store information such as local variation table, operation Stack, dynamic link, method exit, etc. Each method is called until the execution is complete, corresponding to the process of a stack frame in the virtual machine stack from the stack to the stack.

Java memory is often divided into Heap and Stack memory, which is a crude division, and the division of Java memory regions is actually much more complex than that. The popularity of this partition only shows that most programmers care most about these two areas of memory that are most closely related to the allocation of object memory. The “heap” referred to is described later, and the “stack” referred to is the virtual machine stack, or the local variable table part of the virtual machine stack.

Local variable tables store basic data types known at compile time (Boolean, byte, CHAR, short, int, float, long, double), object references (reference types), which are not equivalent to the object itself. It may be a reference pointer to the object’s starting address, a handle to the object or some other location associated with the object, and the returnAddress type (which points to the address of a bytecode instruction).

64-bit long and double data will occupy 2**** of local variable space (Slot), and the rest of the data will occupy only 1. The memory space required for the local variable table is allocated at compile time. When entering a method, how much local variable space the method needs to allocate in the frame is completely determined, and the size of the local variable table does not change during the method run. In the Java Virtual Machine specification, two exceptions are specified for this area: a StackOverflowError is thrown if the stack depth of a thread request is greater than the depth allowed by the virtual machine; If the virtual stack can scale dynamically (and most Java virtual machines currently do, although the Java Virtual Machine specification also allows fixed-length virtual stacks), an OutOfMemoryError will be thrown when sufficient memory cannot be allocated while scaling.

  1. Local method stack

The Native Method stack is similar to the virtual machine stack, except that the virtual machine stack performs Java methods (i.e. bytecodes) for the virtual machine, whereas the Native Method stack services the Native methods used by the virtual machine. The virtual machine specification does not mandate the language, usage, or data structure of methods in the local method stack, so specific virtual machines are free to implement it. There are even virtual machines (such as the Sun HotSpot VIRTUAL machine) that simply merge the local method stack with the virtual machine stack. Like the virtual stack, the local method stack area throws StackOverflowError and OutOfMemoryError exceptions.

  1. The Java heap

For most applications, the Java Heap is the largest chunk of memory managed by the Java virtual machine. The Java heap is an area of memory that is shared by all threads and is created when the virtual machine is started. The sole purpose of this memory area is to hold object instances, and almost all object instances are allocated memory here. This is described in the Java virtual machine specification is: all the object instance and array on the heap allocation, but with the development of the JIT compiler and escape analysis technology of mature gradually, on the stack allocation, replacement scalar optimization technology will lead to some subtle changes, all objects are allocated on the heap also gradually become no longer an “absolute”.

The Java Heap is the primary area managed by the Garbage collector, so it is often referred to as the “Garbage Collected Heap”. From the point of view of memory collection, the Java heap can be subdivided into: new generation and old generation; More detailed are Eden space, From Survivor space, To Survivor space, etc. From a memory Allocation perspective, it is possible to allocate Thread Local Allocation Buffers (TLabs) that are private to multiple threads in a Java heap shared by threads. However, no matter how to partition, it has nothing to do with the storage content, no matter which area, the storage is still the object instance, the purpose of further partition is to better reclaim memory, or faster allocation of memory. In this chapter, we only discuss the role of memory regions; the details of allocation and reclamation of each of these regions in the Java heap will be the subject of the next chapter.

According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory space, as long as it is logically contiguous, like our disk space. When implemented, it can be either fixed size or extensible, but most current virtual machines are implemented as extensible (controlled by -xmx and -xMS). OutOfMemoryError is thrown if there is no memory in the heap to complete the instance allocation and the heap can no longer be extended.

  1. Methods area

The Method Area, like the Java heap, is an Area of memory shared by threads that stores information about classes loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on. Although the Java Virtual Machine specification describes the method area as a logical part of the Heap, it has an alias called non-heap, which is supposed to distinguish it from the Java Heap.

For developers who are used to developing and deploying applications on the HotSpot VIRTUAL machine, many prefer to refer to the method area as “Permanent Generation “. In essence, the two are not equivalent, simply because the HotSpot VIRTUAL machine design team chose to extend GC Generation collection to the method area. Or to implement method sections using persistent generation. For other virtual machines (BEA JRockit, IBM J9, etc.) there is no concept of a permanent generation. Even the HotSpot VIRTUAL machine itself, according to the official roadmap, is now planned to abandon the permanent generation and “move” to Native Memory to implement the method area.

The Java Virtual Machine specification is very relaxed about this area, in addition to the fact that, like the Java heap, it does not require contiguous memory and has the option of either fixed size or scalability, and optionally does not implement garbage collection. Garbage collection is relatively rare in this area, but it is not the case that data enters the method area as “permanent” as the name of the permanent generation. The target of memory reclamation in this area is mainly for constant pool reclamation and type unloading. Generally speaking, the “performance” of the reclamation in this area is not satisfactory, especially for type unloading, but the reclamation in this part of the area is really necessary. Several serious bugs on Sun’s BUG list have been memory leaks caused by earlier versions of the HotSpot VIRTUAL machine not fully reclaiming this area. According to the Java Virtual Machine specification, OutOfMemoryError is thrown when the method area cannot meet memory allocation requirements.

  1. Run-time constant pool

The Runtime Constant Pool is part of the method area. The Constant Pool Table is used to store various literals and symbolic references generated at compile time. This part of the Constant Table is stored in the runtime Constant Pool of the method area after the Class is loaded. The Java virtual machine has strict rules on the format of each part of a Class file (including, of course, the constant pool), and each byte must be used to store what data must conform to the specification before it is accepted, loaded, and executed by the virtual machine. The Java Virtual Machine specification does not specify any details about runtime constant pools, however, and virtual machines implemented by different vendors can implement this memory area as they see fit. However, in general, in addition to storing symbolic references described in Class files, translated direct references are also stored in the runtime constant pool. The Java language does not require constants to be generated only at compile time. That is, the contents of the constant pool in the Class file can be entered into the method area runtime constant pool. New constants may also be added to the pool during runtime. One feature that developers use most often is the Intern () method of the String class. Since the runtime constant pool is part of the method area, it is naturally limited by the method area memory, and an OutOfMemoryError is thrown when the constant pool can no longer claim memory.

  1. Object access

With an introduction to the Runtime data area of the Java Virtual machine, we can explore the question: how does object access work in the Java language? Object access is ubiquitous in the Java language and is the most common program behavior, but even the simplest access involves the relationship between the Java stack, the Java heap, and the method area, the three most important areas of memory, as shown in this code:

Object obj = new Object();

Assuming that this code appears in the method body, the semantics of the “Object obj” section will be reflected in the Java stack’s local variation table as a reference type of data. The semantics of the “new Object()” part will be reflected in the Java heap, forming a structured memory that holds all the Instance Data values of type Object(the Data of each Instance field in the Object). Depending on the type and Object Memory Layout implemented by the VIRTUAL machine, the size of the Memory block is not fixed. In addition, the Java heap must contain the address information where the object type data (such as object type, parent class, implemented interface, method, and so on) can be found, which is stored in the method area.

In the Java Virtual Machine specification, the reference type only specifies a reference to an object, and does not define which way the reference should be located or the specific location of the object in the Java heap. Therefore, different virtual machines implement different object access methods. There are two main access methods: Use handles and direct Pointers. If the handle access method is used, a block of memory will be allocated to the Java heap as the handle pool. Reference stores the handle address of the object, and the handle contains the specific address information of the instance data and type data of the object, as shown in the figure below:

      

If direct pointer access is used, the layout of the Java heap object must consider how to place the information related to the access type data. Reference directly stores the object address, as shown in the following figure:

      

The main advantage of using the handle access method is that ****reference stores a stable handle address and only changes the instance data pointer in the handle when the object is moved (which is a very common behavior in garbage collection). Reference itself does not need to be modified. The biggest benefit of using direct pointer access is that it is faster. It saves the time cost of a pointer location, and since objects are accessed very frequently in Java, this overhead can add up to a very significant execution cost. In the case of Sun HotSpot, the main virtual machine discussed in this book, it uses the second approach for object access, but it is also common across the software development spectrum for languages and frameworks to use handles for access.

 

Three: object oriented: ★★★★★

class

Anonymous object usage scenarios:

1: Anonymous objects can be used when a method is called only once.

2: Anonymous objects cannot be used when objects make multiple calls to members. You must give the object a name.

 

Why is there no main function defined in the class?

Note: The main function exists only if the class needs to be run independently. If not, the main function is not defined.

The main function is guaranteed to run independently of the class, is the entry of the program, called by the JVM.

 

Differences between member variables and local variables:

1: Member variables are defined directly in the class.

Local variables are defined in methods, parameters, and statements.

2: Member variables are valid in this class.

A local variable is valid only within its own brace. The brace ends and the local variable is out of scope.

3: Member variables exist in heap memory, as the object is created, disappear and disappear.

Local variables exist in stack memory and are released when the region to which they belong runs.

 

Constructor: used to initialize an object, is given to the corresponding object to initialize, it has specific, one of the functions.

Features:

1: The name of this function is the same as the name of its class.

2: Return value types do not need to be defined.

3: This function has no concrete return value.

Remember: all objects need to be initialized before they can be used when they are created.

 

Note: When a class is defined, if the constructor has not been defined, the class will automatically generate a null parameter constructor. To facilitate the class to create objects, complete initialization. If you define a constructor in a class, the default constructor is gone.

 

There can be multiple constructors in a class, which can only be distinguished by argument lists because they all have the same function name. So, if there are multiple constructors in a class. They exist in terms of overloading.

 

What is the difference between a constructor block and a constructor?

Construct code block: initializes all objects, that is, all objects call a code block. As long as object one is created. This code block is called.

Constructor: initializes the corresponding object. It’s targeted.

  1. Execution order :(priority from high to low.) Static code block > Mian Method > Construct code Block > Constructor. The static code block is executed only once. The construction block is executed each time an object is created.
  2. What static code blocks do: For example, we can put.so files here when we call C’s dynamic library.
  3. The ability to construct a code block :(you can write the same common things in different constructors into it). For example, if any computer model has the power on function, we can define this function in the construction code block.

 

Person p = new Person();

What does creating an object do in memory?

1: First load the person. class file in the specified location on the hard disk into memory.

2: When the main method is executed, space for the main method is opened in the stack memory (push-push), and then a variable p is allocated in the stack area of the main method.

3: create a physical space in heap memory, allocate a memory header value. new

4: Space allocation of attributes in the entity space and default initialization.

5: Initializes the display of attributes in the space.

6: Initializes the entity construction code block.

7: Initializes the constructor by calling the corresponding constructor of the entity. (a)

8: Assign the first address to p, and the p variable references the entity. (Pointing to the object)

 

 

Encapsulation (one of the object-oriented characteristics) : Hides the attributes and implementation details of an object and provides only public access.

Benefits: Isolation of change; Easy to use; Improve reusability; Security.

Principle of encapsulation: Hide content that does not need to be provided externally, hide attributes, and provide public access to them.

 

This: represents the object. Is a reference to the object that the function belongs to.

What does this stand for? The object that calls this represents the object, and this is a reference to that object.

When do you use this during development?

When defining a function, use this to represent the object that calls the function if the function uses it internally.

 

This can also be used for calls between constructors.

Call format: this(actual argument);

Member attributes and member methods (generic methods) are called after this object.

This, followed by (), calls the constructor for the corresponding argument in this class.

 

Note: Calling the constructor with this must be defined on the first line of the constructor. Because the constructor is used for initialization, the initialization action must be performed. Otherwise, the compilation fails.

 

Static: ★★★ is a modifier used to modify members (member variables and member functions).

Features:

1. Static variables

Class member variables can be classified into two types according to whether they are static or not: one is the variable modified by static, called static variable or class variable; The other type is a variable that is not modified static, called an instance variable. The difference between the two is:

For static variables, there is only one copy in memory (to save memory), and the JVM allocates memory for static variables only once, during class loading. Static variables can be accessed directly (conveniently) by the class name, or by objects (but this is not recommended).

For instance variables, memory is allocated once before an instance is created, and instance variables can have multiple copies in memory without affecting each other (flexible).

2. Static methods

Static methods can be invoked directly by the name of the class, any instance of also can be called, so can’t use this in a static method and the super keyword, cannot directly access the class’s instance variables and instance methods (that is, without a static member variables and members of the member method), can only access static members of a class of affiliation member variables and methods. Because instance members are associated with specific objects! This needs to understand, want to understand the truth among them, not memory!!

Because static methods are independent of any instance, static methods must be implemented and cannot be abstract.

Static code block

A static code block is a static statement that is independent of a class member. It is not in any method. The JVM executes this static code block when loading a class. The JVM executes them in the order in which they appear in the class, and each code block is executed only once.

4. What is static and final together

Static final is used to modify member variables and methods.

For variables, the representation is not modifiable once given a value and is accessible by class name.

For methods, the representation is not overridden and can be accessed directly by the class name.

 

Remark:

1. Some data is object specific and cannot be statically modified. Because then, the specific data becomes the shared data of the object. That’s the wrong way to describe things. Therefore, when defining static, it must be clear whether the data is shared by objects.

2. Static methods can only access static members, not non-static members.

For example, if A class has multiple members (attributes, methods, fields) and A static method, you can access other static members of the same class. If you access non-static members, you cannot.

Because static methods exist before objects when they are loaded, there is no way to access members in an object.

3, static methods cannot use this, super keyword.

Because this represents an object, when static, there may be no object, so this cannot be used.

4. The main function is static.

 

The difference between a member variable and a static variable:

1. The object to which a member variable belongs. So they’re also called instance variables.

A static variable belongs to a class. So they’re also called class variables.

2. Member variables exist in heap memory.

Static variables exist in the method area.

3. Member variables exist as the object is created. Disappears as the object is reclaimed.

Static variables exist as the class is loaded. Disappear as the class disappears.

4. Member variables can only be called by objects.

Static variables can be called by objects as well as by class names.

So, member variables can be called the object’s unique data, and static variables are called the object’s shared data.

 

Static code block: is a block area identified with static keywords. Defined in a class.

Function: Can complete the initialization of a class. Static code blocks are executed as the class is loaded, and only once (new multiple objects are executed only once). If in the same class as the main function, it takes precedence over the main function.

 

final

Depending on the program context, the Java keyword final has the meaning of “this is immutable” or “final state” and can modify non-abstract classes, non-abstract class member methods, and variables. You may need to block change, design, or efficiency for one of two reasons.

Final classes cannot be inherited, there are no subclasses, and methods in final classes are final by default.

Final methods cannot be overridden by subclass methods, but can be inherited.

Final member variables represent constants and can only be assigned once, after which the value does not change.

Final cannot be used to modify constructors.

Note: Private member methods of a parent class cannot be overridden by subclass methods, so methods of private type are final by default.

1, the final class

Final classes cannot be inherited, so the member methods of a final class have no chance of being overridden; they are all final by default. When designing a class, if the class does not need subclasses, the implementation details of the class are not allowed to change, and you are sure that the class will not be extended, then design it as final.

2. Final methods

If a class does not allow subclasses to override a method, the method can be declared final.

The final method is used for two reasons:

First, lock the method to prevent any inherited classes from changing its meaning and implementation.

Second, efficient. When a final method is called, the compiler will turn to the embedded mechanism, which greatly improves execution efficiency.

3. Final variables (constants)

Constants with final modified member variables cannot be changed once given!

Final modifies three types of variables: static variables, instance variables, and local variables, representing three types of constants.

As you can see from the following example, once a final variable has been given an initial value, it cannot be changed.

In addition, when a final variable is defined, it can be declared first without giving an initial value. This variable is also called final whitespace. In any case, the compiler ensures that blank final is initialized before it can be used. However, final whitespace provides greater flexibility in the use of the final keyword final, so that final data members ina class can be implemented to vary from object to object, yet have the property of remaining constant.

4. Final parameters

When a function argument is final, you can read and use it, but you cannot change its value.

 

 

Generate Java help documents: command format: javadoc -d folder name – auther – version *.java

/ * * / / format

* class description

* @ the author the author name

* @ version version number

* /

/ * *

* Method description

*@param Parameter description

*@return Indicates the return value

* /

 

 

Inheritance (one of the object-oriented characteristics)

Java supports only single inheritance for inheritance. Java does not support multiple inheritance directly, but it can implement multiple interfaces.

 

1: member variable.

When an object of the subclass type calls the property when the same property occurs in the subclass, the value is the property value of the subclass.

If you want to call an attribute value in a parent class, you need to use a keyword: super

This: represents an object reference of This class type.

Super: refers to the memory space reference in the parent class to which the subclass belongs.

Note: there is no member variable with the same name in the parent class, because once defined in the parent class, the child class does not need to define it, and can inherit it directly.

2: member function.

When an identical method appears in a child class, the subclass object runs the method in the child class. As if the methods in the parent class were overwritten. So in this case, there’s another property of functions: rewriting

3: constructor.

When the subclass constructor is found to be running, the superclass constructor is run first. Why is that?

The reason: The first line of all constructors of subclasses actually has an invisible super() statement;

Super (): represents the constructor of the parent class and calls the constructor in the parent class corresponding to the argument. Super (), on the other hand, is the constructor that calls the hollow arguments of the parent class.

Why do subclass objects always need to call functions in their parent class when they are initialized? (Why add super() in the first line of the subclass constructor?)

Because a subclass inherits data from its parent class, it must see how the parent class initializes its own data. So when a subclass initializes an object, it first calls the constructor of the parent class, which is the instantiation process of a subclass.

 

Note that all constructors in a subclass access the empty argument constructor in the parent class by default, because the first line of each subclass constructor has the default super() statement;

If there is no null argument constructor in the parent class, then the super statement must be used to specify the constructor in the parent class to access.

If a subclass constructor uses this to specify that the subclass’s own constructor is called, then the called constructor will also access the constructor in the parent class.

 

Question:

Can super() and this() occur together in constructors?

Only one of two statements can be defined on the first line, so only one of them can appear.

Super () or this(): Why must it be defined in the first line?

Since both super() and this() call constructors, which are used for initialization, the initialization action is done first.

 

Two points to note when covering methods:

1: When a subclass overwrites its parent class, it must ensure that the permission of the subclass method is greater than or equal to that of the parent class method to achieve inheritance. Otherwise, the compilation fails. (For example, if a subclass reduces access to a method that is public in its parent class to private, then the overridden method in the subclass is not accessible to external objects, which breaks the meaning of inheritance.)

2: When overwriting, either all static or none static. (Static can only overwrite or be overwritten by static)

 

One drawback of inheritance is that it breaks encapsulation. Some classes, or their functions, need to be inherited or overwritten.

How do you solve the problem? Introduce a keyword, final.

 

Final features :(see above for detailed explanation)

1: This keyword is a modifier that modifies classes, methods, and variables.

2: A final class is a final class and cannot be inherited.

3: A final method is a final method and cannot be overridden.

4: A final variable is a constant and can only be assigned once.

 

Abstract class: abstract

Abstract class features:

1: Abstract methods can only be defined in abstract classes. Abstract classes and methods must be modified by the abstract keyword (classes and methods can be described, not variables).

2: Abstract methods define only method declarations, not method implementations.

3: Abstract classes cannot be created objects (instantiated).

4: A subclass can only be instantiated if it inherits an abstract class and overwrites all the abstract methods in the abstract class. Otherwise, the subclass is an abstract class.

 

Details of the abstract class:

1: Is there a constructor in the abstract class? Yes, used to initialize subclass objects.

2: Can non-abstract methods be defined in abstract classes?

* * * *. In fact, there is no big difference between abstract class and general class, they are describing things, but when abstract class describes things, some functions are not concrete. So both abstract classes and general classes, by definition, need to define properties and behaviors. However, there is one more abstract function than the normal class. And there is one less section for creating objects than normal classes.

3: Abstract keyword and which can not coexist? final , private , static

4: Can abstract classes not define abstract methods? You can. The purpose of the abstract method is simply to prevent the class from creating objects.

 

 

Interface: u u u u u

1: is defined with the keyword interface.

2: members contained in an interface, most commonly global constants, abstract methods.

Note: Members in interfaces have fixed modifiers.

Member variable: public static final

Member method: public abstract

interface Inter{

    public static final int x = 3;

    public abstract void show();

}

3: The interface contains abstract methods, which indicates that the interface cannot be instantiated. A subclass of an interface must implement all abstract methods in the interface before it can be instantiated. Otherwise, the subclass is an abstract class.

4: There is an inheritance relationship between classes, and an implementation relationship between classes and interfaces.

Extends; Implements with implements;

5: The difference between interfaces and classes is that interfaces can be multi-implemented, which is the result of multi-inheritance improvement. Java embodies multiple inheritance through multiple realities.

6: A class can implement multiple interfaces while inheriting from another class. So interfaces avoid the limitations of single inheritance. You can also extend a class’s functionality.

7: There is actually multiple inheritance in Java. Interfaces inherit from each other. Interfaces can inherit from multiple interfaces.

Java classes are single-inherited. classB Extends classA

Java interfaces can have multiple inheritance. Interface3 Extends Interface0, Interface1, interface……

The main reason for disallowing multiple inheritance of classes is that if A inherits both B and C, and both B and C have A method D, how does A decide which one to inherit?

But interfaces don’t have that problem. Interfaces are all abstract methods that inherit from nobody, so interfaces can inherit from multiple interfaces.

 

Abstract classes and interfaces:

Abstract class: it is generally used to describe a system unit and extract a group of common content. Features: Abstract content can be defined in the class for the subclass to implement, and non-abstract content can be defined for the subclass to use directly. It defines the basics of the system.

Interface: Generally used to define the extended functionality of an object, which is required of the object in addition to inheritance.

 

The commonality of abstract classes and interfaces: both are the result of continuous extraction.

 

The difference between abstract classes and interfaces:

1: Abstract classes can only be inherited, and only inherited.

Interfaces need to be implemented, and can be implemented more than once.

2: Non-abstract methods can be defined in abstract classes, and subclasses can directly inherit and use them.

Interfaces are abstract methods that require subclasses to implement.

3: The abstract class uses is A relation.

The like A relationship used by the interface.

4: Member modifiers of abstract classes can be customized.

Member modifiers in interfaces are fixed. They’re all public.

 

Polymorphic u u u u u

Polymorphism ★★★★★ (one of the object-oriented characteristics) : the function itself has polymorphism, a certain thing has different concrete embodiment.

 

Embodiment: a parent class reference or interface reference refers to its own subclass object. // Animal a = new Cat(); A parent class can call methods overridden by a child class.

Benefits of polymorphism: improved program extensibility. Inheriting a parent class or interface is usually something in the class library. The only way to override a method is to use a subclass to call the overridden method by pointing the parent class’s application to an instance of the subclass.

The downside of polymorphism: when a parent reference points to a subclass object, it increases extensibility, but can only access methods that exist in the parent class, not methods that are specific to the subclass. (In the early stage, the functionality generated in the later stage cannot be used, i.e. access limitations)

The premise of polymorphism:

1: There must be relationships, such as inheritance, or implementation.

2: There is usually an overwrite operation.

 

If you want to use methods specific to subclass objects, how do you determine which specific subclass type an object is?

You can use a keyword instanceof; // Determine whether the object implements the specified interface or inherits the specified class

 

Format: < object instanceof type > determines whether an object belongs to the specified type.

Student instanceof Person = true; // Student inherits the Person class

 

————————————————————————————-java.lang.Object

Object: The direct or indirect parent class of all classes. Java believes that all objects have some basic common content, which can be continuously extracted to the top class, which defines the functions of all objects.

 

Specific methods:

  1. Boolean equals(Object obj) : Compares the addresses of two objects.

2, String toString() : turns an object into a String; The default returned format: Class name @hash = getClass().getName() + ‘@’ + integer.tohexString (hashCode())

In order to make the corresponding string content of the object meaningful, we can set up the unique string representation of the object by copying.

    public String toString(){

        return “person : “+age;

    }

3, Class getClass() : Gets the bytecode file object of any object run time.

4, int hashCode() : Returns the hash value of the object. This method is supported to improve the performance of hash tables. Converts the internal address of the object to an integer.

 

In general, equals, toString, and hashCode are all overridden in an application, creating specific content for specific objects.

————————————————————————————-

 

Inner class: If class A needs to access members of class B directly, and class B needs to create objects of class A. At this point, class A is defined directly in class B for ease of design and access. That’s it. Class A is called an inner class. Inner classes have direct access to members of outer classes. In order for an external class to access an inner class, it must create an object for the inner class.

—————————————————–

class Outer{

    int num = 4;    

    class Inner {

        void show(){

            System.out.println(“inner show run “+num);

        }

    }

    public void method(){

Inner in = new Inner(); // Create an object for the inner class.

in.show(); // Call the inner class method. // An inner class accesses an outer class member directly, using its own instance object;

****} // The outer class accesses the inner class to define the object of the inner class;

}

——————————————————-

When an inner class defines member positions in an outer class, you can use some member modifiers to modify private and static.

1: default modifier.

Direct access inner class format: Outer class name. Inner class name Variable name = outer class object. Inner class object;

Outer.Inner in = new Outer.new Inner(); // This form is rarely used.

But this is rare, because inner classes are defined internally for encapsulation. To get an inner class object, you usually get it from the methods of the outer class. This gives you control over internal class objects.

2: private modifier.

Inner classes are usually privatized when encapsulated, because encapsulation does not allow other programs to access them directly.

3: static modifier.

If the inner class is statically decorated, as in the outer class, there are access limitations and only static members of the outer class can be accessed.

Note; If static members are defined in an inner class, the inner class must be static.

 

The compiled file name of the inner class is “Outer class name $Inner class name.java”.

 

Why can an inner class directly access a member of an outer class?

That’s because each inside holds a reference to an external class. This is the reference to the external class name.this

An inner class can be defined at a member location in an outer class, or at a local location in an outer class.

When an inner class is defined at a local location, only local variables that are modified by final in the local can be accessed.

 

Anonymous inner class (object) : An inner class without a name. It’s a simplified form of the inner class. You can use this form only once. An anonymous inner class is simply an anonymous subclass object. To define an anonymous inner class: the inner class must inherit a class or implement an interface.

 

The format of the anonymous inner class: new superclass name & interface name (){define subclass members or override superclass methods}. Methods.

 

Anonymous inner class usage scenarios:

When the parameter of a function is an interface type reference, if there are no more than three methods in the interface. Parameters can be passed through anonymous inner classes.

When creating an anonymous inner class, it is best to encapsulate two or fewer methods in the class.

——————————————————–

/ / the interview

/ / 1

        new Object(){

            void show(){

                System.out.println(“show run”);                

            }

} .show(); // Both writing and compiling are ok

/ / 2

        Object obj = new Object(){

            void show(){

                System.out.println(“show run”);

            }

        };

obj.show(); // Write the correct, compile error

        

Are 1 and 2 written correctly? Is there a difference? Say why.

Both 1 and 2 create an Object subclass from an anonymous inner class.

The difference between:

The first one compiles and runs.

The second compilation fails because the anonymous inner class is a subclass Object that is promoted to Object when referred to by Object’s obj reference, and the compilation fails when the Object class is checked for the show method.

 

 

Is: u u u u

– Java. Lang. Throwable:

Throwable: something that can be thrown.

| – Error: Error, in general, not specific code for processing, is usually the JVM, need to modify the program.

| – Exception: abnormal, can be targeted treatment

 

All classes and objects in this system have a unique characteristic; That’s the disposability.

The expression of throwability is that all classes and objects in this system can be operated by throws and throws.

 

Throws throws

Throws is used to declare all exception information that a method may throw, while throws refers to a specific exception type thrown. In addition, throws is to declare an exception but not process it, but to upload the exception, who calls me to handle it.

Throw throws an exception object, followed by an exception object; Throw is used in functions.

Throws exception classes. Multiple exception class names can be followed by throws. Separate the names with commas (,). Throws is used on functions.

 

Throws method name (parameter) throws exception class 1, exception class 2,…..

Throw: performs exception processing on its own. There are two methods for exception processing: either catch an exception (that is, try catch) or declare throwing an exception (that is, throws exception ~~).

 

There are two processing methods: 1. Capture; 2. Throw.

For capture: Java-specific statement blocks.

try {

Code that needs to be detected;

}

Catch (exception class variable name){

Exception handling code;

}

fianlly{

Code that must be executed;

}

 

When defining exception handling, when do you define a try and when do you define throws?

If an exception occurs within a function, use a try if it can be handled internally.

If the function cannot handle it internally, it must declare it and let the caller handle it. Throws using throws and passes to the caller for processing. Whoever calls this function is the caller;

 

Steps for customizing exceptions:

1: Define a subclass that inherits Exception or RuntimeException and makes it throwable (throw and throws are used to call this class).

2: Operations are performed using throw or throws.

 

The idea of exception conversion: When an exception occurs that the caller cannot handle, it needs to be converted into an exception thrown that the caller can handle.

 

Several combinations of try Catch Finally:

1,

try

catch

finally

 

In this case, if an exception occurs, it is not handled, but the resource must be closed, so the try Finally collection only closes the resource.

Remember: Finally is useful, and the primary user closes the resource. Resources must be shut down regardless of whether an exception occurs.

System.exit(0); // Exit the JVM only if finally is not executed.

 

Note:

If a parent class or interface method does not throw an exception, a subclass cannot throw an exception. If an exception occurs in a method overridden by a subclass, only try does not throw.

Throw a RuntimeException or its subclass if the exception subclass cannot be handled and has affected the operation of the subclass method, then throw a RuntimeException or its subclass in the subclass method. In this way, the method of the subclass does not require a throws declaration.

 

 

Multithreading: ★★★★

Return the name of the currentThread: thread.currentthread ().getname ()

The name of a Thread is defined by: thread-number. The numbers start at 0.

The code that a thread runs is stored in the run method.

 

A thread must be started using a method specified in the class to run. The start method. (After startup, there is one more execution path)

Start method: 1) Start the thread; 2) Let the JVM call the run method.

 

The difference between the run() and start() methods in Thread:

Start () : The start method is used to start the thread, which truly implements multi-threaded running, without waiting for the body of the run method to finish executing. A Thread is started by calling the start() method of the Thread class. The Thread is in a ready state, but is not running. As soon as the CPU slice is available, the run() method is executed. The thread then terminates.

Run () : the run () method is a common way of class, if direct call run method, this thread is still only the main thread in the program, the program execution path or there is only one, or to order, still want to wait until after the run method body has been completed can continue to execute the following code, so that no writer threads.

Conclusion: The essential function of the start() method is to request another thread space from the CPU to execute the code in the run() method. It is separate from the current thread and runs in a relatively separate thread space. That is, if you call the run() method of the thread object directly, it will also execute, but that is Execute in the current thread, and continue with the following code after the run() method completes. When the start() method is called, the code for the run() method executes concurrently (single-CPU) or concurrently (multi-CPU) with the current thread. So keep this in mind: calling the run method on a thread object does not create a new thread, although the same result can be achieved, but the execution process and efficiency are different

 

The first way to create a Thread is to inherit Thread and subclass the run method.

Steps:

1. Define a class that inherits Thread.

2. The purpose is to replicate the run method by storing all the code that the thread is running in the run method.

Create Thread objects by creating a subclass of Thread.

4. Call the thread’s start method, start the thread, and execute the run method.

 

Thread status:

Created: start()

Operation: having the executive qualification and the executive power;

Freeze: sleep(time),wait() — notify(); The thread releases the execution right and the execution qualification;

Temporary blocked state: the thread has the CPU execution qualification, not the CPU execution right;

Die: stop ()

The second way to create threads is to implement an interface called Runnable.

Steps:

1. Define a class that implements the Runnable interface.

Override the run method in the interface (used to encapsulate the code that the thread is running).

3. Create Thread objects through the Thread class.

4, Pass the subclass object implementing the Runnable interface as an actual parameter to the constructor in Thread.

Why pass it on? The thread object needs to know which object the run method to run belongs to.

Call the start method of the Thread object. Start the thread and run the run method in the Runnable interface subclass.

Ticket t = new Ticket();

/ *

Create the Ticket object directly, not the thread object.

You can only create objects from the New Thread class, or a subclass of the New Thread class.

So eventually you want to create threads. Since there are no subclasses of Thread, we can only use Thread.

* /

Thread t1 = new Thread(t); // Create a thread.

/ *

The association between the Thread object and T is accomplished by passing t as the actual argument to the constructor of the Thread class

Why pass T to the Thread constructor? This is to specify the code run method that the thread should run.

* /

        t1.start();

        

Why the Runnable interface?

1: The establishment of multithreading can be completed by inheriting Thread class. However, there is a limitation to this approach. If a class already has its own parent class, it cannot inherit Thread because of the limitations of Java single inheritance.

However, there are parts of the code in this class that need to be executed simultaneously by multiple threads. What do you do?

Java provides an interface, Runnable, only with additional functionality extensions to the class. This interface defines the run method, in fact, the run method is defined to store multithreaded code to run.

As a result, threads are usually created the second way.

Because implementing the Runnable interface avoids the limitations of single inheritance.

 

2: In fact, it is to extract the code that needs to be executed by multi-threading in different classes. Define the location of multithreaded code to run separately into the interface. It provides the premise for other classes to extend functions.

So when Thread describes threads, the internally defined run method also comes from the Runnable interface.

 

Implementing the Runnable interface avoids the limitations of single inheritance. In addition, inheriting Thread allows you to subclass the methods in Thread. But it’s easier to implement the Runnable interface without having to do this, just to define where thread code is stored. So the Runnable interface encapsulates the tasks a thread is supposed to perform as objects.

——————————————————-

/ / the interview

New Thread(new Runnable(){// Anonymous

            public void run(){

                System.out.println(“runnable run”);    

            }

        })

 

        {

            public void run(){

                System.out.println(“subthread run”);

            }

}.start(); // Result: subthread run

———————————————————

Synchronized keywords (1)

When two concurrent threads access the synchronized(this) block of the same object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing the code block before executing it.

2. However, when one thread accesses a synchronized(this) block of an object, another thread can still access a non-synchronized (this) block of that object.

3. In particular, when one thread accesses a synchronized(this) block of an object, access to all other synchronized(this) blocks in the object is blocked by other threads.

The third example also applies to other synchronized code blocks. That is, when a thread accesses a synchronized(this) block of an object, it acquires the object lock. As a result, access by other threads to all synchronized code parts of the object is temporarily blocked.

The above rules also apply to other object locks.

 

package ths;

public class Thread1 implements Runnable {

public void run() {

synchronized(this) {

for (int i = 0; i < 5; i++) {

System.out.println(Thread.currentThread().getName()+”synchronized loop ” + i);

}

}

}

}

 

Synchronized keywords (2)

The synchronized keyword, which has two uses: a synchronized method and a synchronized block.

1. Synchronized method: Declare a synchronized method by adding the synchronized keyword to the method declaration. Such as:

public synchronized void accessVal(int newVal);

The synchronized method controls access to class member variables: Each synchronized method must obtain the lock of the class instance calling the method before it can be executed. Otherwise, the owning thread will be blocked. Once executed, the method will monopolize the lock until it is released when it returns from the method. This mechanism ensures that at most one member function declared synchronized is in an executable state for each class instance at any one time (because at most only one can acquire the lock corresponding to the class instance), Thus, access conflicts for class member variables are effectively avoided (as long as all methods that can access class member variables are declared synchronized).

In Java, not only class instances, but also each class has a lock, so we can also declare a class’s static member functions as synchronized to control access to the class’s static member variables.

Drawbacks of synchronized method: Declaring a large method as synchronized can greatly affect efficiency. Typically, declaring the thread class’s method run() as synchronized, since it runs throughout the lifetime of a thread, As a result, any calls it makes to synchronized methods of this class will never succeed. Of course we can get around this problem by putting code that accesses class member variables into a special method, declaring it synchronized, and calling it in the main method, but Java provides a better solution: synchronized blocks.

2. Synchronized blocks: Declare synchronized blocks by using the synchronized keyword. The syntax is as follows:

synchronized(syncObject) {

// Allow access control code

}

A synchronized block is a block of code in which the code must acquire a lock on the object syncObject (which, as mentioned earlier, can be an instance of a class or a class) in order to execute, using the same mechanism as before. Flexibility is high because you can target any block of code and specify any locked object.

Some understanding of synchronized(this)

When two concurrent threads access the synchronized(this) block of the same object, only one thread can be executed at a time. Another thread must wait for the current thread to finish executing the code block before executing it.

2. However, when one thread accesses a synchronized(this) block of an object, another thread can still access a non-synchronized (this) block of that object.

3. In particular, when one thread accesses a synchronized(this) block of an object, access to all other synchronized(this) blocks in the object is blocked by other threads.

The third example also applies to other synchronized code blocks. That is, when a thread accesses a synchronized(this) block of an object, it acquires the object lock. As a result, access by other threads to all synchronized code parts of the object is temporarily blocked.

The above rules also apply to other object locks.

 

Principles of solving security problems:

This problem can be solved by allowing one thread to execute statements that operate on shared data at a certain time, while no other thread can enter.

How do you make shared data thread safe?

Java provides a solution: synchronize blocks of code.

Format:

Synchronized {// any object can be synchronized. This object is shared data.

Code to be synchronized;

}

—————————————————————

Synchronous: u u u u u

Benefits: Solves thread safety issues. Synchronized

Disadvantages: Relatively low performance, because determining locks consumes resources, resulting in deadlocks.

 

 

The second form of synchronization: // Define synchronization for methods that share resources

Synchronization function: in fact, the synchronization keyword is defined in the function, so that the function has synchronization.

 

Which lock does the synchronization function use? //synchronized(this) defines the part of the code block that needs to be synchronized

By verification, functions have their own object this, so the lock used by synchronization functions is this lock. This method name

 

When a synchronization function is modified static, which lock is used for synchronization?

When a static function is loaded, it belongs to a class. At this time, there may be no object generated by the class, but the bytecode file of the class has been encapsulated as an object when loaded into memory. This object is the bytecode file object of the class.

So when statically loaded, only one object exists, and that object is used by the statically synchronized function.

That object is the class name.class

 

What’s the difference between a synchronized code block and a synchronized function?

The lock used by the synchronized code block can be any object.

The lock used by the synchronization function is this, and the lock used by the static synchronization function is the bytecode file object of that class.

 

If you have only one synchronization in a class, you can use a synchronization function. If there is multiple synchronization, blocks of synchronization code must be used to determine the different locks. So synchronized code blocks are relatively flexible.

——————————————————-

Please write a lazy load singleton pattern? Write in lazy style; How to solve the problem of multi-threaded access? Add synchronization, solve security problems; Is it efficient? Is not high; How to solve it? It’s solved in the form of a double judgment.

// Lazy: lazy loading.

When multiple threads access lazy methods, because lazy methods operate on common data in multiple statements. So it’s easy to have thread safety issues. To solve the problem, add synchronization mechanism to solve the security problem. But it has resulted in a loss of efficiency.

For efficiency, the problem is solved in the form of dual judgment.

class Single{

    private static Single s = null;

    private Single(){}

Public static Single getInstance(){ Bytecode file object;

        if(s == null){

synchronized(Single.class){

if(s == null)

s = new Single();

}

}

        return s;

    }

}

———————————————————

Wake-on-wait mechanism: Methods involved:

Wait: Freezes the thread being synchronized. Release of executive power, release of qualifications. The thread object is also stored in the thread pool.

Notify: wakes up a waiting thread in the thread pool.

NotifyAll: Wakes up all threads in the thread pool.

 

Note:

1: These methods need to be defined in synchronization.

2: Because these methods must identify the lock to which they belong.

If the thread on lock A is waited, it is in the thread pool of lock A and can only be awakened by the notify of lock A.

3: All three methods are defined in the Object class. Why are methods for manipulating threads defined in the Object class?

Since all three methods need to define a synchronization and identify the lock they belong to, methods that can be called by any Object must be defined in the Object class since the lock can be any Object.

 

The difference between wait and sleep:

Wait: Time can be specified or not specified. The time is not specified. Only notify or notifyAll can be used to wake up the alarm.

Sleep: The time must be specified to automatically transition from frozen state to running state (temporary blocked state).

Wait: The thread releases execution, and the thread releases the lock.

Sleep: The thread releases execution, but not the lock.

 

Stop a thread: A thread can be stopped using the stop method. But that’s out of date.

Stop the thread: The principle is: let the thread running code end, that is, end the run method.

How do I end the run method? A normal run method must define a loop. So just close the loop.

The first way: define the end tag of the loop.

Second, if the Thread is frozen and it is impossible to read the token, it needs to be forcibly cleared of the frozen state via the Interrupt method in the Thread class. Restores the thread to an executable state so that it can read the tag and terminate.

 

———< java.lang.Thread >———-

Interrupt () : Interrupts a thread.

SetPriority (int newPriority) : Changes the priority of a thread.

GetPriority () : Returns the priority of the thread.

ToString () : Returns a string representation of the thread, including the thread name, priority, and thread group.

Thread.yield() : Suspends the currently executing Thread object and executes other threads.

SetDaemon (true) : Marks this thread as a daemon or user thread. Mark this thread as a daemon thread or a user thread. The Java virtual machine exits when all running threads are daemons. This method must be called before starting the thread.

Join: You can use the join method to temporarily join a thread.

When thread A performs the join mode of thread B. Thread A is frozen, freeing execution, and thread B starts execution. A When will it be implemented? Only after thread B finishes running, A resumes running from the frozen state.

 

 

LOCK appears instead of synchronization: lock. LOCK (); …… lock.unlock();

Lock interface: multithreading in the JDK1.5 update, the introduction of an interface Lock interface.

The solution to thread-safety problems is in the form of synchronization (synchronization of code blocks, or synchronization of functions), which ultimately uses locking mechanisms.

 

In later versions, locks are wrapped directly into objects. When a thread enters synchronization, it has the lock, and when it leaves synchronization, it releases the lock.

In the later analysis of the lock, it was found that the action of obtaining the lock or releasing the lock should make the lock more clear. So these actions are defined in the lock and the lock is defined as an object.

 

So synchronization is an implicit Lock operation, and the Lock object is an explicit Lock operation, and its presence replaces synchronization.

 

In previous versions, wait, notify, and notifyAll of the Object classes were used to do this. That’s because locks in synchronization are arbitrary objects, so wake-up methods that operate on locks are defined in the Object class.

 

Now the Lock is a specified object Lock. So finding the wake-on-wait mechanism is done through the Lock interface. The Lock interface does not directly manipulate wake-up methods, but encapsulates them in an object. This Object is the Condition, which encapsulates the three methods in Object separately. It also provides uniformly functional methods await(), signal(), signalAll() to show the benefits of the new version of the object.

< Java util. Concurrent. The locks > Condition interfaces: await (), signal (), signalAll ();

——————————————————–

class BoundedBuffer {

final Lock lock = new ReentrantLock();

final Condition notFull = lock.newCondition();

final Condition notEmpty = lock.newCondition();

final Object[] items = new Object[100];

int putptr, takeptr, count;

public void put(Object x) throws InterruptedException {

lock.lock();

try {

while (count == items.length)

notFull.await();

items[putptr] = x;

if (++putptr == items.length) putptr = 0;

++count;

notEmpty.signal();

}

finally {

lock.unlock();

}

}

public Object take() throws InterruptedException {

lock.lock();

try {

while (count == 0)

notEmpty.await();

Object x = items[takeptr];

if (++takeptr == items.length) takeptr = 0;

–count;

notFull.signal();

return x;

}

finally {

lock.unlock();

}

}

}

 

Collections framework

Collection framework: ★★★★★, a container for storing data.

 

For collection containers, there are many kinds. Because each container has different characteristics, the principle is that each container has a different internal data structure.

The collection container is in the process of being continuously pumped up. We have aggregate systems.

When working with a system, the rule is: see the top-level content. Create the underlying object.

————————————————————

–< java.util >– List interface

The List itself is a subinterface of the Collection interface, with all the methods of Collection. Now we learn the unique common methods of the List system. When we look up the methods, we find that the unique methods of the List all have indexes, which is the biggest feature of this set.

 

List: Ordered (elements are put into the collection in the same order as they are taken out). Elements are indexed. Elements can be repeated.

| – ArrayList: the underlying data structure is an array, threads are not synchronized ArrayList instead of the Vector, the speed of query element is very high.

| – LinkedList: the underlying data structure is a linked list, thread synchronization, add or delete elements of speed is very fast.

| – Vector, the underlying data structure is an array, thread synchronization, the Vector both query and add or delete the giant is slow.

 

 

Variable-length arrays work:

When an element exceeds the array length, a new array is created, the data of the original array is copied to the new array, and the new element is added to the new array.

ArrayList: is extended by 50% of the original array. Construct an empty list of initial capacity 10.

Vector: extends by 100% of the original array.

————————————————————

–< java.util >

Data structure: How data is stored;

Methods in the Set interface are the same as those in Collection. There is only one way to retrieve the Set interface, iterator.

| – HashSet: the underlying data structure is a hash table, thread is out of sync. Disorder, efficient;

The HashSet collection guarantees element uniqueness: this is done through the elements’ hashCode and equals methods.

If the elements’ hashCode values are the same, we continue to check whether equals is true.

If true, it is treated as the same element and does not exist. If false, store.

If hashCode values are different, equals is not judged to speed up object comparisons.

| – LinkedHashSet: orderly, hashset subclass.

| – TreeSet: Set to the Set of elements in the specified order. Out of sync. The underlying data structure of TreeSet is the binary tree.

 

For an ArrayList collection, checking whether elements exist or are deleted is based on equals.

In the case of a HashSet collection, the underlying method to determine whether elements exist or are deleted is the hashCode and Equals methods.

 

————————————————————

Map collections:

| – Hashtable: is the underlying hash table data structure, is a thread synchronization. You cannot store null keys, null values.

| – HashMap: is the underlying hash table data structure, thread is out of sync. You can store null keys, null values. Replace the Hashtable.

| – TreeMap: the bottom is a binary tree structure, the order of the keys of the map set can be specified.

 

Map Collection storage is very different from Collection:

Collection stores one element at a time; Map stores one pair of elements at a time.

A Collection is a single-column Collection. A Map is a collection of bicolumns.

A Map stores a pair of elements: a key and a value, and there is a mapping between the keys and the values.

Features: Ensure that the keys in the map set are unique.

 

5, want to get all elements in the map:

There are no iterators in a map. A collection has iterators. If you convert a map to a Set, you can use iterators. The reason why it is changed to set is that map set has the uniqueness of keys. In fact, set set comes from Map, and map method is actually used at the bottom of set set.

  • To convert a map set to a set:

Set keySet();

Set entrySet(); // select a mapping between keys and values.

Entry is the internal interface of the Map interface.

Why define it inside a map? Entry is the entry to access key-value relationships. It is the entry to access key-value pairs in the map.

———————————————————

The keySet() method is used to retrieve all elements in the map set.

You can take all the keys from the map set and put them in the set set. Iterate over the set set. Iteration is completed, and then get the value of the obtained key through get method.

        Set keySet = map.keySet();

        Iterator it = keySet.iterator();

while(it.hasNext()) {

Object key = it.next();

Object value = map.get(key);

System.out.println(key+”:”+value);

}

——————————————————–

The entrySet() method is used to retrieve all elements in the map set.

Set entrySet = map.entrySet();

        Iterator it = entrySet.iterator();

        while(it.hasNext()) {

            Map.Entry me = (Map.Entry)it.next();

            System.out.println(me.getKey()+”::::”+me.getValue());

        }

——————————————————–

 

Methods for turning unsynchronized Collections into synchronized Collections: XXX synchronizedXXX(XXX) in Collections;

List synchronizedList(list);

Map synchronizedMap(map);

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {

return new SynchronizedMap<K,V>(m);

}

Principle: define a class that returns all methods in a collection with the same lock.

List list = Collections.synchronizedList(new ArrayList());

Map<String,String> synmap = Collections.synchronizedMap(map);

 

The difference between Collections and Collections:

Collections, a java.util class, is a utility class for Collections that provides a set of static methods for finding, sorting, replacing, and thread-safe operations on Collections (converting unsynchronized Collections to synchronized ones).

Collection is an interface under Java.util. It is the parent interface of various Collection structures. The main interfaces inherited from Collection are Set and List, which provide some operations on Collection, such as inserting, deleting, determining whether an element is a member, traversing, etc.

——————————————————-

Automatic unboxing: There are two types of data types in Java: Basic data types Reference data types (objects)

All data needs to be treated as objects in Java programs. There are wrapper classes for eight basic data types, as follows:

int –> Integer

byte –> Byte

short –> Short

long –> Long

char –> Character

double –> Double

float –> Float

boolean –> Boolean

 

In jdK5, the basic data types and wrapper classes need to be interconverted:

Integer x = new Integer(x);

Reference — basic int num = x.ntValue ();

1), Integer x = 1; x = x + 1; What was the process? Packing a unpacking A packing;

2) For optimization purposes, the virtual machine provides a buffer pool for the wrapper class. The size of the pool is from -128 to 127 bytes.

3) String pool: Java provides a buffer pool to optimize String operations;

———————————————————-

Generics: a security mechanism that has emerged since jdk1.5. Format: < >

Benefits:

1: Turn the runtime ClassCastException problem into a compile failure, which the programmer can fix at compile time.

2: Avoid the trouble of casting.

 

Wildcard in generics: can solve the problem when the specific type is uncertain, this wildcard is? ; When operating on types without the specific functions of the type, only the functions of the Object class are used. So you can use it? Wildcard to list unknown types.

———————————————————————————————————————— ——-

 

Reflection technology

Reflection technique: Essentially loading a specified class dynamically and fetching all the contents of that class. And encapsulate the contents of the bytecode file as objects, making it easy to manipulate the members. Simply put: Reflex technology can anatomize a class.

 

The benefit of reflection: greatly enhances the extensibility of the application.

 

Basic steps of reflection:

1, get the Class object, is to get the name of the bytecode file object.

Instantiate the object to get a property, method, or constructor of the class.

3. Access properties, call methods, and call constructors to create objects.

 

There are three ways to get this Class object:

1: get by the method getClass that is available to each object. Drawback: You must create the class object before you can call the getClass method.

Each datatype (base datatype and reference datatype) has a static attribute class. Disadvantages: The class must be identified first.

The first two methods are not conducive to program extension because they require the use of specific classes in the program.

3: static forName method used in the Class Class.

The most extensible approach is to get the bytecode file object of any class name you specify, simply by passing in a string of the class name.

// 1. Get for class loading based on the given class name

String classname = “cn.itcast.reflect.Person”; // from the configuration file

Class clazz = Class.forName(classname); // This object represents Person.class

// 2. What type is used to obtain the type of the object

Object obj = new Person();

Class clazz1 = obj.getClass(); // Get the specific type of the object

// 3. If a Class object is explicitly obtained, it is mainly used for passing arguments

Class clazz2 = Person.class;    

 

Use of reflection:

1) To obtain the components of a Java Class, you need to obtain the Class object first. There are three ways to obtain the Class object:

Class.forname (className) is used for Class loading

Obj.getclass () is used to get the type of the object

Class is used to get the specified type and pass the parameter

 

Reflection class member method:

    Class clazz = Person.class;

    Method method = clazz.getMethod(methodName, new Class[]{paramClazz1, paramClazz2});

    method.invoke();

    

Reflection class constructor:

Constructor con = clazz.getConstructor(new Class[]{paramClazz1, paramClazz2,… })

    con.newInstance(params…)

 

4) Reflection class attributes:

    Field field = clazz.getField(fieldName);

    field.setAccessible(true);

    field.setObject(value);

 

After obtaining the bytecode file object, we eventually need to create an object of the specified class:

There are two ways to create an object (which is how it is initialized when instantiated) :

Call the empty argument constructor using the Class newInstance() method.

2. Call the constructor with arguments: First get the constructor object with the specified argument list, and then initialize the object with newInstance(the actual argument) on the constructor object.

 

In the second method, we must first specify the type of the constructor argument, which is not easy to extend. So in general, reflected classes usually provide a constructor for a public empty argument.

——————————————————

// How to generate the instance object that gets the bytecode file object.

Class clazz = Class.forName(“cn.itcast.bean.Person”); / / class loading

Get the specified type directly

        clazz = Person.class;

// Get the type based on the object

        Object obj = new Person(“zhangsan”, 19);

        clazz = obj.getClass();

 

Object obj = clazz.newInstance(); // The method call to the instantiated object specifies the null parameter constructor of the class to initialize the created object. How do you create an object for a specified class that does not have a null parameter constructor? Please see method_2 ();

    public static void method_2() throws Exception {

        Class clazz = Class.forName(“cn.itcast.bean.Person”);

// Since there is no constructor for empty arguments in the class, only the constructor that takes the specified argument is instantiated with that function.

// Get a constructor with arguments.

        Constructor constructor = clazz.getConstructor(String.class,int.class);

// To initialize an object, use the constructor’s method newInstance();

        Object obj = constructor.newInstance(“zhagnsan”,30);

// Get all constructors.

Constructor[] constructors = clazz.getConstructors(); // Only public

constructors = clazz.getDeclaredConstructors(); // Contains private

        for(Constructor con : constructors) {

            System.out.println(con);

        }

    }

——————————————————

Reflection specifies a method in a class:

// Get all the methods in the class.

    public static void method_1() throws Exception {

        Class clazz = Class.forName(“cn.itcast.bean.Person”);

Method[] methods = clazz.getMethods(); // Get the public methods in the class and the public methods in the parent class.

methods = clazz.getDeclaredMethods(); // Get methods in this class, including private methods.

        for(Method method : methods) {

            System.out.println(method);

        }

    }

// Get the specified method;

    public static void method_2() throws Exception {

        Class clazz = Class.forName(“cn.itcast.bean.Person”);

// Get the method of the specified name.

        Method method = clazz.getMethod(“show”, int.class,String.class);

To run a specified method, of course, the method object knows best. In order for the method to run, we simply call the invoke method of the method object, but the method to run must specify the object to which it belongs and the actual parameters.

        Object obj = clazz.newInstance();

method.invoke(obj, 39,”hehehe”); // Execute a method

    }

// You want to run private methods.

    public static void method_3() throws Exception {

        Class clazz = Class.forName(“cn.itcast.bean.Person”);

// Want to get private methods. Must use getDeclearMethod ();

        Method method = clazz.getDeclaredMethod(“method”, null);

Private methods cannot be accessed directly because they do not have enough permissions. If you have to, you can do it by force.

method.setAccessible(true); // Private means hidden, so try not to access it.

    }

// reflect static methods.

    public static void method_4() throws Exception {

        Class clazz = Class.forName(“cn.itcast.bean.Person”);

        Method method = clazz.getMethod(“function”,null);

        method.invoke(null,null);

    }

\