JAVA basics + entry + knowledge that must be mastered

JAVA basics

Three basic characteristics of object-oriented

Package

  • Encapsulate objective things into an abstract class, and the class can operate its own data and methods only by trusted classes or objects, and hide information from untrusted ones

inherit

  • Allows objects of a certain type to obtain properties and methods of objects of another type

Polymorphism

  • Refers to a class instance of the same method has different performance in different situations

Five principles

Single responsibility principle

  • Refers to a class with a single function, not all-encompassing

Open and closed principle

  • A module should be open for expansion and closed for changes

Replacement principle

  • Subclasses should be able to replace the parent class and appear anywhere in the parent class

Dependency principle

  • Concretely depends on abstraction, upper layer depends on lower layer

Interface separation principle

  • Modules must be separated by abstract interfaces, not strongly coupled by concrete classes

== The difference between equals?

1. The equals method compares the contents of two objects
2. == Compares whether two objects are the same object, or compares whether the memory addresses of the objects are the same (for basic types, == compares two Are the values ​​of the two equal? ​​For reference types, == compares whether the reference addresses are the same)


The difference between static variables and instance variables?

1. The static variable belongs to the class, and the static variable can be directly called by the class name
2. The instance variable belongs to the object, and the object of the class must be generated before the instance variable can be called


What is the difference between overload (method overload) and override (method override)?

Method overloading occurs when two or more methods in the same class have the same method name but different parameters.
Method coverage When it comes to redefining the method of the parent class, the method coverage must have the same method name and parameter list And return value type


What is the difference between abstract class and interface?

1. All the methods in the interface are implicitly abstract, and abstract classes can contain both abstract and non-abstract methods

2. A class can implement many interfaces, but it can only inherit an abstract class

3. If the class wants to implement an interface, then all methods in this interface must be implemented. But the class may not implement all the methods in the abstract class. Of course, in this case, the class must also be an abstract class.

4. The variables declared in the Java interface are final by default, and abstract classes can contain non-final variables

5. The member functions in the Java interface are public by default, and private protected or public can be in the abstract class

6. The interface is absolutely abstract and cannot be instantiated. An abstract class cannot be instantiated, but if it has a main method, it can be called.


What is the difference between stringBuilder and stringBuffer?

String is a string constant, which is modified by final. stringBuffer is a thread-safe string variable; stringBuilder is a thread-unsafe variable.

String is an immutable object. Each operation on the string type is equivalent to generating a new string object, so try not to perform a lot of stitching on the string, otherwise a lot of temporary objects will be generated, causing the GC to start working and affecting system performance.
StringBuffer and StringBuilder operate on the object itself, rather than generating new objects.
Note: The JVM will have certain optimizations for String stitching, such as: String s = "hello" + "world"; it
will be directly optimized by the JVM to String s = "helloworld", there is no stitching at this time;


Common methods of string:
charAt (int index)
equals ()
substing ()
trim ()
length ()
indexOf ()
endsWith ()
startWith ()
equalsIngorCase ()
uppstring ()
toLower ()
toUpCase ()


What is the difference between running abnormal and general abnormal?

Abnormality indicates an abnormal state that may occur during the running of a program. Runtime abnormality indicates an abnormality that may be encountered in the operation of a virtual machine. It is a common operating error.
The Java compiler requires that a method must throw a non-runtime exception that may occur, but it does not require that it must declare an uncaught runtime exception.


The difference between deep copy and shallow copy?

Shallow copy: All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, shallow copy only copies the object under consideration, not the object he refers to.
Deep copy: All objects of the copied object have the same value as the original object, and variables that refer to other objects will point to the new object that has been copied, instead of the original referenced objects. In other words, deep copying copies all the objects referenced by the objects to be copied.


Is the relationship between equals () and hashCode ()?

hashCode () is a method of the object class, which returns a hash value. If two objects are equal according to the equals () method, then calling the hashCode () method of any one of these two objects will definitely produce the same hash value. . If two objects are not equal according to the equals () method, the hash values ​​generated are not necessarily equal.


The difference between Collection and Collections?

Collection is the superior interface of the collection class. The inherited interfaces are mainly Set and List
Collections. It is a helper class for the collection class. He provides a series of static methods to implement the search, sort, and thread-safe operations for various collections.


What is the difference between list and set?

1. Both list and set are inherited from the collection interface.
2. The list elements are placed in order, and the elements can be repeated. set features. The elements are placed in no order (unordered because his storage location is determined by the hashcode value of the element, which is fixed), and the elements cannot be repeated;
3. The implementation class of the list interface: the implementation class of the LinkedList ArrayList Vector
set collection : HashSet, LinkedHashSet


How to ensure that Set collection is not repeated?

1. Determine whether the hashCode of the two objects are equal.
If they are not equal, the two objects are considered to be unequal and complete;
if they are equal, go to 2.
2. Determine whether the equals () of the two objects
are equal. Objects are not equal

hashCode is mainly to improve storage efficiency.


The difference between process and thread?

A process is an independent running environment, he can be regarded as a program or an application. The thread is a task executed in the process. The Java environment is a single process that contains different classes and programs. Threads require fewer resources to create and reside in the process, and can share resources in the process.

What are the state of the thread?

During the execution of a thread, the thread may be in the following states:
ready: the thread is ready to run, and may not necessarily start execution immediately.
Running: The process is executing thread code.
Waiting: The thread is blocked, waiting for the end of external processing.
Sleeping: Thread is forced to sleep
i / o blocked: Waiting for i / o operation to complete
Synchronous blocking: Waiting to acquire lock
Death: Thread finished executing.

What are the methods of thread synchronization?

1. Synchronized keyword modification method
2. Synchronized keyword modification statement block
3. Thread synchronization using the reentrant lock class
4. Thread synchronization using ThreadLocal management variables
5. Using blocking queues
6. Using atomic variables

How to ensure the orderly execution of several threads?

1. The shared object lock can ensure that only one thread can enter each method. With the wait and nitifyall methods, the thread can be started or changed.
2. Through the main thread join ()

What is the difference between wait and sleep methods in Java?

1. The two methods come from different classes: Thread and Object
2. Sleep does not release the lock, and the wait method has a lock, so that other threads can use the synchronization control block or method
3. Wait notify and notifyAll can only be controlled in synchronization The method or synchronous charge block is used, and the sleep method can be used anywhere.
4. The sleep method must catch exceptions, while wait, notify, and notifyAll do not need to catch exceptions.

yield () method:

Calling yield () will cause the current thread to surrender the CPU permissions and let the CPU execute other threads. Similar to the sleep () method, it will not release the lock. However, yield () cannot control the specific time for handing over the CPU. In addition, the yield () method only allows threads with the same priority to have the opportunity to obtain CPU execution time. In addition, the yield () method does not let the thread enter the blocking state, but To return the thread to the ready state, it just has to wait to reacquire the CPU execution time, which is different from sleep ().


What is the use of ThreadLocal?

He is a class that creates thread local variables. To put it simply, ThreadLocal is a way to exchange space for time. In each Thread, a ThreadLocal.ThreadLocalMap implemented by the open address method is maintained to isolate the data and the data is not shared. Naturally, there are no problems with thread safety.


What is the difference between synchronous and asynchronous in threads?

Synchronization: The A thread is going to request a certain resource, but this resource is being used by B. Because of the existence of the synchronization mechanism, the A thread cannot request a resource and can only wait.

Asynchronous: The A thread is going to request a certain resource, but this resource is being used by B. Because there is no synchronization mechanism, the A thread can still request the resource without waiting.

Briefly describe the thread local variable ThreadLocal?

Thread local variables are variables limited to thread memory, which belong to the thread itself and are not shared among multiple threads. It is a way to achieve thread safety.


Briefly describe the pessimistic locking and optimistic locking of Java multithreading?

Pessimistic locks: No matter whether multi-thread conflicts occur or not, as long as there is such a possibility, every time you access the lock, the lock will lead to contention between the locks.

Optimistic lock: The lock has been held after the lock is obtained to prevent the thread from reapplying the lock to cause fearless unlocking and locking overhead.


When is the finalize () method called and its role?

Before releasing the memory occupied by the object, the garbage collector calls the object's finalize () method. It is generally recommended to release the resources held by the object in this method.


Briefly describe the class loading mechanism and the loading process?

The class starts from being loaded into the virtual machine memory and unloads the memory. His entire life cycle includes seven stages: loading, verifying, preparing, parsing, initializing, using, and unloading. The three parts of verification, preparation and analysis are collectively called linking.

Loading: The loading stage is completed by the class loader, which has the following main functions:
(1) Obtain a binary byte stream defining this class
(2) Convert the static storage structure represented by this byte stream into a runtime data structure in the method area
(3) Generate a Java.lang.Class object representing this class in the Java heap

Verification: Verification is the first step in the connection phase. The purpose of this phase is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not endanger the virtual machine's own security.
Preparation: It is to allocate memory for the static variables of the class and initialize them to default values. These memories will be allocated in the method area.
Resolution: The resolution phase is the process of the virtual machine replacing the symbol references in the constant pool with direct references
: initialization The stage is the process of executing the class constructor () method.

8 basic data types of Java?


								占用字节
byte						1
short						2
int							4
long						8
float						4
double						8
char						2
boolean						1/8
=======================
1byte 		= 	8it
1024byte	=	1kb
1024kb	   	= 	1M
1024m 		= 	1G

The difference between Map and ConcurrentHashMap:

ConcurrentHashMap divides the entire bucket array into segments, that is, segments, and then uses a lock lock to protect each segment. The granularity of the synchronized keyword lock is more refined than HashTable, and the concurrent performance is better, but HashMap does not. The lock mechanism is not thread-safe. The HashMap key value can be null, but ConcurrentHashMap is not allowed!


Brief description of http protocol?

HTTP: Hypertext Transfer Protocol is a stateless, application layer protocol based on request and response mode, often based on TCP connection.
The http request header consists of three parts: the request line, the message header, and the request body. The response is also divided into three parts, the status line (including the http version, status code, and reason phrase of the status code), the response header field, and the response internal entity.


The difference between redirect and forward?

1. Redirection is the behavior of the client, and forwarding is the behavior of the server
2. Redirection of two requests and two responses, forwarding of one request and response of one
3. Redirection can jump to any website, and forwarding can only be forwarded inside the server
4. Redirection will cause the request object information to be lost, and the forwarding will not


What is the function and difference of cookie and session?

1. Cookie data is stored on the client and session is stored on the server.
2. Cookies are insecure. Others can analyze cookies stored locally and spoof cookies. Therefore, important data should be stored on the server using the session.
3. The session will be stored on the server for a certain period of time, but it will occupy memory resources. When too many users are accessed, it will increase the burden on the server. Considering the pressure of the server, unimportant data should be stored on cookies.
4. The data saved by a cookie cannot exceed 4K.


Collection

Single-column collection

List

ArrayList

Realization of the underlying array, fast query, slow addition and deletion, unsafe, high efficiency

The default capacity is 10, which increases by 50% after expansion

LinkedList

The realization of the underlying linked list, slow query, fast addition and deletion, unsafe, high efficiency

Vector

The implementation of the underlying data, adding, deleting and modifying are slow, but safe

The default capacity is 10, and the default loading factor is 1, which is double the original capacity after expansion.

Set

HashSet

The underlying HashMap, subclass LinkedHashSet implementation of the underlying linked list

The default capacity is 16, the load factor is 0.75, and the expansion is doubled

TreeSet

Can be sorted, the underlying binary tree algorithm is implemented

Two-column collection

Map

HashMap

The underlying hash algorithm, for keys, allows null keys and values, thread insecurity, high efficiency, keys cannot be stored repeatedly, values ​​can be

The default capacity is 16, the loading factor is 0.75, and the capacity is doubled after expansion

TreeMap

The bottom layer is a binary tree, which can be sorted for keys

LinkedHashMap

The bottom layer is a hashing algorithm. Like HashSet, the key is unique and the value can be changed.

Dictionary

HashTable

Do not allow null keys and values, thread safety, and low efficiency

The default capacity is 11, the expansion is 2 times + 1


Thread Pool

1、corePoolSize

Number of core threads

After the thread pool is created, by default, there are no threads in the thread pool. Instead, it waits for a task to arrive before creating a thread and fetching the task.
By default, after the thread pool is created, the number of threads in the thread pool is 0. When a task comes, a thread is created to execute the task. When the number of threads in the thread pool reaches corePoolSize, it will be reached. Tasks are cached in the queue, and tasks are assigned for execution when there are threads idle.

2、maxiumPoolSize

The maximum number of threads allowed in the thread pool

The maximum number of threads allowed in the thread pool. If the queue is full, but the number of threads created is less than the maximum number of threads, the thread pool will create new threads to perform tasks.

But if you are using an unbounded queue, this parameter has no effect!

3、keepAliveTime

Indicates how long the thread can be terminated when no task is executed

It indicates how long the thread will terminate when no task is executed.
By default, keepAliveTime will only work when the number of threads in the thread pool is greater than corePoolSize, knowing that the number of threads in the thread pool is not greater than corePoolSize.

In other words, this parameter makes it work on threads larger than corePoolSize and smaller than maximumPoolSize.

4, TimeUnit

Time unit: 7 types in total, nanosecond, subtle, millisecond, second, minute, hour, day

5、workQueue

Save the blocking queue waiting for the task to be executed

synchronousQueue
tag: priority 1

When this queue receives a task, it will directly submit it to the thread for processing instead of retaining it. If all threads are working, then the thread is created. So in order to ensure that there is no error that the number of threads reaches maxiunPoolSize and cannot create threads, when using this queue, generally speaking, maxiunPoolSize is specified as Integer.MAX_VALUE, that is, infinity.

LinkedBlockingQueue
tag: Priority 2

When this queue receives a task, if the current number of threads is less than corePoolSize, then create a new thread to process, if the current number of threads is equal to the number of core threads, then enter the queue to wait, which leads to the invalidation of the maxiumPoolSize setting, because the total number of threads is always Will not exceed corePoolSize.

ArrayBlockingQueue
tag: priority 3

The length of the queue can be set. When the task is received, if the corePoolSize is not reached, a new thread is created. If it is reached, it enters the queue and waits. If the queue is full again, a new thread is created. If the queue is full, an error will be reported.

DelayQueue
tag: priority 4

The elements in the queue must implement the Delayed interface, which means that the tasks you pass in must implement the Delayed interface. After the queue receives the task, it enters the queue first. The task will not be executed until the specified time is reached.

6、ThreadFactory

Thread factory, mainly used to create threads

7、RejectedExecutionHandler

When the queue and the thread pool are full, indicating that the thread pool is saturated, then a strategy must be adopted to handle the submitted new tasks. This policy defaults to (1) AbortPolicy, which means that it cannot throw a new task if it cannot handle a new task. There are 4 types in total, and the other 3 types are: (2) DiscardPolicy means to discard the task without throwing an exception. (3) DiscardOldestPolicy means to discard the first task in the queue, and then try to execute the task again. (4) CallerRunsPolicy indicates that the task is handled by the calling thread.

Published 4 original articles · praised 4 · visits 103

Guess you like

Origin blog.csdn.net/qq_40585384/article/details/105376604