preface

2021 golden nine silver ten will soon enter the recruitment season, now for everyone to sort out this golden nine silver ten interview Ali interview summary, I got from a friend of the interview questions, without saying much, full of dry things to share with you!

Is int a=10 atomic?

Yes.

Note:

  • I ++(or ++ I) is a non-atomic operation. I ++ is a multi-step operation and can be interrupted. I ++ can be divided into three steps, the first step reads I, the second step calculates I +1; The third part assigns the final value to I.
  • int a = b; It’s not atomic. At the syntactic level, this is also a statement, atomic; However, from the perspective of the actual execution of binary instructions, due to the limitations of the CPU architecture system of modern computers, data cannot be directly transferred from memory to another memory, and register interrupt must be used. This statement generally corresponds to two computer instructions, namely, transferring the value of variable B to a register (such as EAX). From this register to the memory address of variable a:
mov eax, dword ptr [b]  
mov dword ptr [a], eax 

Since there are two instructions, when multiple threads are executing these two instructions, one thread may be deprived of the CPU time slice after the execution of the first instruction and switch to another thread, resulting in an uncertain situation.

Does InnoDB support full-text indexing?

The InnoDB storage engine started to support full-text indexing after version 5.6, and Chinese with the use of the Ngram plugin after version 5.7. Previously, only English was supported, because it used Spaces as word separators, which was not appropriate for Chinese. MySQL allows full-text indexing on types char, varchar, and text.

Does InnoDB support table locking?

SQL > add, delete, or delete to a table; add, delete, or add to an index; add, delete, or add to an index; add, delete, or add to an index;

How HTTP short connection becomes long connection.

Add –Connection:keep-alive to the header.

Will the call yeild () block?

Blocking is the suspension of a thread’s execution until a condition occurs, such as when a resource is ready. Yield () : yield() causes the thread to give up CPU time, but does not block the thread, meaning that the thread is still executable and can get another chunk of CPU time at any time. The effect of calling yield() is equivalent to the scheduler deciding that the thread has executed for enough time to move to another thread. Yield () simply brings the current thread back to the executable state, so the thread that executes yield() may be executed again as soon as it reaches the executable state. Sleep () allows the lower-priority thread to execute, as well as higher-priority and same-priority threads. Yield () only gives threads of the same priority a chance to execute.

Is the virtual stack shared by threads?

It isn’t.

The JVM initially allocates the Method Area and the Heap, and for each thread encountered by the JVM, Assign it a Program Counter Register, VM Stack and Native Method Stack. When the thread terminates, all three (VM Stack, Virtual Stack, Native Method Stack) The memory used by the local method stack and program counters is also freed. That’s why I’ve divided the memory regions into thread-shared and non-thread-shared regions, where the life cycle of the three non-thread-shared regions is the same as that of the thread they belong to, and the life cycle of the thread-shared regions is the same as that of the Java program that runs. So this is why the locale for system garbage collection only occurs in the region shared by threads (in fact, on the Heap for most virtual machines).

The stack area:
  • Each thread contains a stack that holds only the value of the underlying data type (such as int I =1, where 1 is an object of the underlying type), a reference to the object and a reference to the underlying data
  • The data in each stack (underlying data types and object references) is private and cannot be accessed by other stacks.
  • The stack is divided into three parts: the base type variable area, the execution context, and the operation instruction area (which holds the operation instruction).
The heap area:
  • All it stores are objects, each of which contains information about a corresponding class. (The purpose of class is to get operation instructions)
  • There is only one heap (heap) in the JVM that is shared by all threads, and there is no base type or object reference in the heap, only the object itself.
Methods area:
  • Also known as a static area, like a heap, is shared by all threads. The method area contains all the class and static variables.
  • The method area contains elements that are always unique in the entire program, such as class and static variables. (The difference between the two is that the heap area stores the new object information, while the method area stores the existing class information.)

In which part of the JVM are constants stored?

Method area: Also known as static area, like heap, is shared by all threads. It is used to store class information, constants, static variables, code compiled by the just-in-time compiler, and other data that has been loaded by the virtual machine.

The window.postMessage() method is safe for cross-source communication. Typically, scripts with two different pages can only communicate with each other if the page on which they are executed is located has the same protocol (usually HTTPS), the port number (443 is the default for HTTPS), and the host (the module document.domain of the two pages is set to the same value). The window.postMessage() method provides a controlled mechanism to circumvent this restriction, and as long as it is used correctly, it is safe.

Are all objects allocated to the heap?

A: Not necessarily.

Is CopyOnWriteArrayList thread safe?

A. Yes. CopyOnWriteArrayList uses a method called copy-on-write. When a new element is added to CopyOnWriteArrayList, it first copies a copy of the original array and then writes to the new array. After that, it points the original array reference to the new array. When we create a new array and add a new element to the new array, the array reference will still refer to the original array. When the element is successfully added to the new array, the reference array is referred to the new array. The entire add operation of CopyOnWriteArrayList is done under the protection of a lock. The reason for this is to avoid making multiple copies of the data when the multiple threads are concurrently adding, which will mess up the data and cause the final array data to be not what we expected.

Public Boolean add(E E) {//1, Final ReentrantLock Lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; //2, Object[] newElements = copyOf(elements, len + 1); NewElements [len] = e; newElements[len] = e; SetArray (newElements); setArray(newElements); return true; } finally {//5, Unlock Lock.Unlock (); }}

Since all writes are performed in the new array, if there are concurrent writes by threads, then the lock is used to control them. If there are concurrent reads by threads, then there are several cases:

  • If the write operation is not completed, then read the original array directly.
  • If the write completes, but the reference does not point to the new array, then the original array is also read.
  • If the write completes and the reference already refers to the new array, the data is read directly from the new array.

CopyOnWriteArrayList can be read without locking. CopyOnWriteArrayList has several disadvantages: If the contents of the original array are too large, Young GC or Full GC may not be used for real-time reading. For example, copying the array and adding new elements will take time. Therefore, after calling a set operation, The read data may still be old. Although CopyOnWriteArrayList can achieve final consistency, it still fails to meet the real-time requirements. CopyOnWriteArrayList is suitable for scenarios where there are too many reads and too few writes, but you should use it with caution because there is no guarantee of how much data you will put in your CopyOnWriteArrayList. If there is too much data, it is too expensive to copy the array every time you add/set. In high-performance Internet applications, this operation can cause failures within minutes. CopyOnWriteArrayList reveals the idea

  • Reading and writing separate, reading and writing separate
  • Final consistency
  • Use the idea of creating additional space to resolve concurrency conflicts

Array out of bounds problem

Typically, we use one thread to add elements to the container, and one thread to read them, which is often more frequent. Write locking ensures thread safety and read/write separation ensures read efficiency. It’s perfect. If a third thread for removing elements operation, read the thread to read the container, the last element in the reading before the container size of I, when to read threads suddenly delete an element, when the container size into the I – 1, read the thread to read the case of an element, I still will occur at this time of an array. To test this, first fill the CopyOnWriteArrayList with 10000 test data and start two threads, one continuously deleting elements and one continuously reading the last data in the container.

    public void test(){
        for(int i = 0; i<10000; i++){
            list.add("string" + i);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (list.size() > 0) {
                        String content = list.get(list.size() - 1);
                    }else {
                        break;
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if(list.size() <= 0){
                        break;
                    }
                    list.remove(0);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

Can Java Interfaces Inherit Multiple?

Java classes are singly inherited. The ClassB extends ClassA Java interface can be multiinherited. Interface3 extends Interface0, Interface1, Interface… The main reason for not allowing multiple inheritance of classes is that if A inherits both B and C, and both B and C have A D method, how does A decide which one to inherit? But interfaces don’t have this problem. They all inherit abstract methods and it doesn’t matter who they are, so interfaces can inherit multiple interfaces.

(byte)300==(byte)100+(short)200?

Answer: false. The value range of byte in Java is -128~127, and when the overflow occurs, the modulus is 256. 130>127 overflow, so the module 256 is 130, still overflow, subtract 256 again to get -126, so S =-126. 300>127 overflows, so module 256 is 44, 44 is within the byte value range, so the binary of S =44. 300 is: 100101100; Byte cast from right to left to take 8 bits: 00101100; Because the eighth bit is 0, it is positive, and we know that the complement of the positive number is the same. So 00101100 is converted to decimal: 44 (32+8+4) (byte)100+(short)200. The result of byte and short will be automatically converted to short without overflowing. So (byte)100+(short)200=(short)300, and (byte)300 results in 44. So they’re not equal.

The operating system has process management, storage management, file management and device management functions. Which of the following statements is not true? (A)

A. Process management is mainly for the management of programs B. Storage management is mainly for the management of memory resources C. File management can effectively support the operation of files, and solve the problems of file sharing, confidentiality and protection. Device management refers to the management of all input and output devices in a computer system except CPU and memory

This and super are correct (C) :

Public static void main(String[] args) public static void main(String[] args) public static void main(String[] args) public static void main(String[] args) public static void main(String[] args) Object-specific this or super keywords cannot be used.

Is reference counting a JVM GC algorithm?

A: is.

Can I throw an exception again in the finally{} of a try{}catch(){}finally{} structure?

A: can. Exception in thread “main” java.lang.Exception: F (finallytry.java :16) at com.test.finallytry.main (finallytry.java :5)

——– Throwing an exception in finally or return will obscure the previous exception

New HTTP2 features?

A: Reduce header size, add request priority, server push, multiplexing.

Can indexes turn random IO into sequential IO?

A: yes. Random IO: Assuming we need data are randomly dispersed in the pages of different sectors of the disk, and then find the corresponding data need to wait until the spin magnetic arm (addressing) to the specified page, and then find the corresponding plate sector, to find what we need a piece of data, in order for this process until you find all the data, this is a random IO, Slow data reading. Sequential IO: Assuming that we have found the first block of data, and that all the other required data are behind this block, then we can retrieve the required data in sequence without needing to readdress it. This is called sequential IO.

Are transient modified variables temporary?

A: yes.

  • Once a variable is modified transient, the variable is no longer part of the object’s persistence, and the contents of the variable cannot be accessed after serialization.
  • Transient keywords can only modify variables, not methods and classes. Note that local variables cannot be modified with transient keywords. If the variable is a user-defined class variable, the class needs to implement the Serializable interface.
  • Variables decorated with transient keywords can no longer be serialized. A static variable cannot be serialized regardless of whether it is decorated with transient keywords. Note: In Java, object serialization can be done by implementing two interfaces. If you implement the Serializable interface, then all serialization will be done automatically. If you implement the Externalizable interface, then nothing can be serialized automatically. The variables to serialize need to be specified manually in the writeExternal method, regardless of whether they are modified by transient.

High, medium and low level scheduling.

Advanced scheduling: that is, job scheduling, according to a certain strategy to select the program on the disk into memory, and establish the process. Intermediate scheduling (existing in a multi-batch system) : Switching scheduling, in which data is exchanged between internal and external storage according to a certain strategy. Low-level scheduling: that is, CPU scheduling (process scheduling), according to a certain strategy to select the ready process, occupy the CPU execution. Among them, low degree scheduling is necessary.

Is port 80 occupied?

  • A: ps – ef | grep 80
  • Method 2: netstat anp | grep: 80
  • Lsof -i:80
  • Pattern 4: netstat tunlp | grep: 80
  • Pattern 5: netstat – an | grep: 80

C++ weak reference pointer is what?

Weak_ptr is also a reference-counting smart pointer, but it does not increase the reference count of the object, that is, weak reference. In contrast, shared_ptr is a strong reference, and as long as there is a shared_ptr pointing to an object, the object will not be destructed until the last shared_ptr destructor or reset() pointing to the object. Using Weak_PTR, we can solve the common dangling pointer problem and circular reference problem.

The following non-class constructors are characterized by ().

  • A. No return value
  • B. The user can call it automatically with new.
  • C. The constructor name must be the same as the class name
  • D. Users can call it directly
  • A D [parse] constructor is a special method in a class that is written for an object initialization operation to define the initial state of the object. Every class in the Java language has a constructor, which is also made up of a method name, parameters, and method body. The constructor name must be the same as the class name, it has no return value, and the user cannot call it directly, it can only be called automatically through new.

At what level does the SPX protocol work?

SPX(Sequenced Packet Exchange Protocol) is a protocol developed by Novell and used in NetWare to ensure the successful transfer of information. SPX uses NetWare’s IPX protocol as its delivery mechanism and provides client-server and tier-to-tier interaction between network nodes. It works at the transport layer.

Why did TCP wait 2MSL after the fourth wave before disconnecting? Why is the waiting time 2MSL?

  • A: 1. In order to ensure that the message of the client’s last wave can reach the server, if the message segment of the fourth wave is lost, the server will retransmit the message segment of the third wave over time. Therefore, the client does not directly enter Closed at this time, but maintains TIME_WAIT (waiting for 2MSL is TIME_WAIT). When the client receives the third wave request due to timeout retransmission, the client sends the fourth wave message back to the server (to ensure that the server can receive the response message from the client). Finally, the client and server are really disconnected. To put it bluntly, waiting for 2MSL is to ensure that the server receives the final response from the client.
  • 2. If the client closes directly and then initiates a new connection to the server again, there is no guarantee that the port number of the newly initiated connection will be different from that of the newly CLOSED connection. It is possible that the port number of the new connection and the old connection will be the same. Assuming that the port number of the new and old connection is the same, if some of the data of the old connection is still stuck in the network, and the data does not arrive at the server until the new connection is established. Given that the port number before and after the new connection is the same, the TCP protocol assumes that the data belongs to the new connection, so the data is in a mess. So the TCP connection also waits for 2MSL in the TIME_WAIT state to make sure that all the old connection data is gone from the network!
  • MSL is the abbreviation of Maximum Segment Lifetime (Maximum Segment Lifetime), which is the Maximum Lifetime of any packet on the network. Once the time is exceeded, the packet will be discarded. 2MSL means 2 times MSL time. Why is it 2 times?
  • The actively disconnected side is A, and the passively disconnected side is B.
  • First message: A sent FIN
  • Second message: B reply ACK
  • Third message: B sends FIN At this point: B unilaterally believes that it has reached an agreement with A that both parties have agreed to close the connection. At this point, can B release the memory resources occupied by the TCP connection? No, B must make sure that A receives his ACK and FIN. So B needs to wait quietly for the arrival of the fourth message from A:
  • Fourth message: A sends an ACK to confirm receipt of B’s FIN

When B receives this message, it is considered that both parties have reached synchronization: both parties know that the connection can be released, and B can safely release the memory resources and port number used by this TCP connection. So passively closed B releases the resource without any wait time. However, A doesn’t know if B has received his ACK. Here’s what A thinks: 1) if you didn’t receive your B ACK, will timeout retransmission FiN so again received A retransmission FiN, will once again send an ACK 2) if B receive their ACK, also won’t send any messages, including an ACK either 1 or 2, A need to wait for, to take in both cases the maximum wait time, in response to the worst, The worst case is: the maximum time to ACK messages (MSL) + the maximum time to FIN messages (MSL). This is exactly 2MSL(Maximum Segment Life). After waiting for 2MSL, A can safely release the TCP resources and port number, which can be used to connect to any server at this time. At the same time can also ensure that the old links in the network all disappeared.

What are the states of the process and describe them briefly?

  • There are 5 basic states of a process, that is, create state, ready state, run state, block state, and stop state.
  • Create state: When the process is created, it needs to apply for a blank PCB, fill in the information of controlling and managing the process, and complete the resource allocation.
  • Ready state: A process is ready, has been allocated the required resources, and is ready to run as soon as it is allocated to the CPU.
  • Execution state: When a process is scheduled, it enters the execution state.
  • Blocked state: The executing process is temporarily unable to run due to some event and the process is blocked.
  • Terminated state: The process ends, or an error occurs, or is terminated by the system. It enters the terminated state and cannot be executed again.
  • Process refers to a program running on a data set in a computer, which is the basic unit of resource allocation and scheduling in the system.
  • Process state means that the life cycle of a process can be divided into a group of states, which describe the whole process, and process state is the life state of a process.

Create NIO client code.

package com.cn.niochat; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Scanner; Throws IOException {public void start() throws IOException {/** * Links to server */ SocketChannel SocketChannel = socketChannel. Open (new InetSocketAddress (8000) "127.0.0.1,"); Scanner Scanner = new Scanner(system. in); While (scanner.hasNextLine()){String request = scanner.nextLine(); // if(request! = null && request.length() > 0){ socketChannel.write(Charset.forName("UTF-8").encode(request)); } } } public static void main(String[] args) throws IOException { NioClient nioClient = new NioClient(); nioClient.start(); }}

What are the ways to get a Class instance of a class?

  • (1). Invoke the.class attribute class clazz = string.class;
  • (2), public final Class
    getClass() is non-static. Person p = new Person(); The Class clazz = p.g etClass ();
  • (3) a static Class method: reflecting the dynamic String className = “java.util.mons”; The Class clazz = Class. Class.forname (className);
  • (4) String ClassName = “java.util.mons” by the class loader; This this = this. GetClass (). GetClassLoader (); The Class claz. = this loadClass (className);

The frequency of a, b, c, d, e and f characters are 16, 5, 12, 17, 10 and 25, respectively. What is the minimum number of bytes encoded?

25+16+17 times 2+12 times 3+ 5+10 times 4=212.

What is the best object in MySQL to get a record of the result set and do special operations on it?

Cursor.

System.out.println(1+1+ “1”) prints 21. System. The out. Println (” 1 + 1 + 1 “); The output of 111.

Java’s + expression evaluates from left to right. If there are two integers, the value will be evaluated. If one of them is a String, the value will be concatenated and the result will be a String. 1+1+ “1”, first calculate 1+1, because both are plastic, evaluation =2, then 2+” 1″, splicing, so it is 21, while “1” +1+1, first calculate” 1″ +1, because there is a String, the result is’ 11″, then “11” +1 is” 111 “.

Member variables, static methods on the left; Non-static methods: compile to the left, run to the right.

When a parent variable refers to a child object (Fu f = new Zi();) The reference variable f refers to an object whose member variables and static methods are identical to the parent class. Its non-static methods are identical to the parent class at compile time but are identical to the child class at run time (copying occurs).

class Fu { intnum = 5; static void method4() { System.out.println("fu method_4"); } void method3() { System.out.println("fu method_3"); } } class Zi extends Fu { intnum = 8; Static void method4() {// Note that static methods cannot overwrite System.out.println("zi method_4"); } void method3() { System.out.println("zi method_3"); } } class DuoTaiDemo4 { public static void main(String[] args) { Fu f = new Zi(); System.out.println(f.num); // same as the parent f.method4(); // same as the parent f.method3(); Zi z = new Zi(); Zi z = new Zi(); System.out.println(z.num); z.method4(); z.method3(); }}

HTTP status code beginning with 1

  • A status code that represents a temporary response and requires the requester to continue the operation.
  • 100 (Continuing) The requester should continue to make the request. The server returns this code to indicate that it has received the first part of the request and is waiting for the rest.
  • 101 (Switching Protocol) The requester has asked the server to switch the protocol. The server has acknowledged and is ready to switch.

HTTP status code beginning with 2

  • Indicates that the request succeeded
  • 200 successfully processed the request, normally return this status code;
  • The 201 request was successful and the server created a new resource.
  • 202 Accepts request but does not create resource;
  • 203 return a request for another resource;
  • 204 server successfully processed the request, but did not return anything;
  • 205 server successfully processed the request, but did not return anything;
  • 206 handles partial requests;

3xx (redirect)

  • Redirect code, also common code
  • 300 (multiple options) The server can perform a number of actions on a request. The server can select an operation according to the requester (User Agent) or provide a list of operations for the requester to select.
  • 301 (permanently moved) requested page has been permanently moved to a new location. When the server returns this response (the response to a GET or HEAD request), it automatically forwards the requester to the new location.
  • The 302 (Temporary Mobile) server is currently responding to requests from a Web page in a different location, but the requester should continue to use the original location for future requests.
  • 303 (View other locations) The server returns this code when the requester should use a separate GET request for a different location to retrieve the response.
  • 304 (Unmodified) The requested page has not been modified since the last request. When the server returns this response, the Web page content is not returned.
  • 305 (using proxies) requestors can only use proxies to access requested web pages. If the server returns this response, it also indicates that the requester should use the proxy.
  • The 307 (temporary redirect) server is currently responding to requests from a Web page in a different location, but the requester should continue to use the original location for future requests.

The HTTP status code starting with 4 indicates an error

  • The 400 server does not understand the syntax of the request.
  • 401 requests require authentication. For pages that require login, the server may return this response.
  • The 403 server refused the request.
  • 404 server could not find the requested page.
  • 405 Disables the method specified in the request.
  • 406 Unable to respond to the requested page with the requested content feature.
  • 407 This status code is similar to 401, but specifies that the requester should authorize the use of the agent.
  • A timeout occurred while the 408 server was waiting for a request.
  • The 409 server collided while completing the request. The server must include information about the conflict in the response.
  • 410 If the requested resource has been permanently deleted, the server returns this response.
  • The 411 server will not accept requests that do not contain a valid content-length header field.
  • The 412 server did not meet one of the prerequisites set by the requester in the request.
  • The 413 server could not process the request because the requesting entity was too large for the server to handle.
  • The request URI (usually the URL) is too long for the server to process.
  • The format of the 415 request is not supported by the requested page.
  • If the page does not provide the requested scope, the server returns this status code.
  • 417 server did not meet the “expected” request header field requirement.

The five-start status code is not common, but we should know

  • 500 (server internal error) The server encountered an error and could not complete the request.
  • The 501 (not yet implemented) server does not have the capability to complete the request. For example, the server might return this code if it is unable to recognize the requested method.
  • The 502 (error gateway) server, acting as a gateway or proxy, received an invalid response from the upstream server.
  • 503 (service unavailable) The server is currently unavailable (due to overload or downtime for maintenance). Usually, this is a temporary situation.
  • The 504 (gateway timeout) server acts as a gateway or proxy, but does not receive a request from the upstream server in time.
  • The 505 (HTTP version is not supported) server does not support the HTTP protocol version used in the request.
  • Memory: 1 pro (temporary response) 2 into (request successful) 3 direct (redirect) 4 please (request error) 5 server error

Pen test

One, multiple choice questions

1. In the Java language, access rights limited to methods of subclasses or classes in the same package are (C).

A, public

B, private

C, protected

D. No decoration

Analysis of the

Private: The narrowest modifier in the Java language that restricts access permissions, commonly referred to as “private.” Attributes and methods decorated by it are accessible only to objects of the class, not to subclasses, and not to cross-package access.

Default: No access modifier, often referred to as “default access” or “package access”. In this mode, access is only allowed within the same package.

Protected: An access modifier between public and private, commonly referred to as “protected access”. Attributes and methods that are decorated by them can only be accessed by methods of the class itself and by subclasses, even if the subclasses are accessible in different packages.

Public: The most restricted-access modifier in the Java language, commonly referred to as “public”. It modifies classes, properties, and methods that can be accessed not only across classes, but also across packages.

2. Among the following alternative methods, the method belonging to the interface MousEmotionListener is (D).

A and mouseReleased ()

B, mouseEntered ()

C, mouseExited ()

D, mouseMoved ()

3. The following is the statement about threads. The correct one is (C).

A. The use of multi-threading can improve the parallel working ability of the device, but it makes the system management complicated

B. Each thread in the same process has its own state, dedicated data segment, and independent memory resources

C, A thread is a program that can run independently

D. The execution efficiency of a process is higher than that of a thread

4. When writing a Java program that accesses a database, the ResultSet object does (D)

A, Create A new database connection B, Use to represent the connection to the database

C, Processes SQL statements in the specified connection

D. Store the query results

5. Which is true about the method main ()? (C)

A. The method main () can only be placed in a public class

The header definition for b.ain () can be changed arbitrarily depending on the situation

C. A class can have no main() method

D. All objects must be created in the main() method

6. Abstract method: (C)

A. There can be method body (wrong) B. Can appear in a non-abstract class

C. It’s a method without a method body

D. All methods in an abstract class are abstract methods

7. This and super: (C)

A. Both can be used in the main() method

B. Both refer to a memory address

C. Cannot be used in the main() method

D. The same meaning

8. The difference between a character stream and a byte stream is (D)

A. The former is buffered, the latter is not

B. The former is a block read and write, the latter is a byte read and write

C. There is no difference between them and they can be used interchangeably

D. The number of bytes per read and write varies

9. Class B is an abstract class, and class C is a non-abstract subclass of class B. The following statement creates object X1. (abstract classes cannot be instantiated, that is, objects cannot be created)

A.B x1= new B( );

B x1= C();

C x1=new C();

C x1= new B();

10. In the life cycle of A thread object, which is not the state it experiences (A).

(Five basic states: New; Ready; Run; Block; Death)

A. interrupt

B. run

C. ready

D. death

11. What kind of layout object can change the position of the corresponding control with the width of the window (A)

A, FlowLayout

B, GridLayout

C, BordyLayout

D, CardLayout

12. For import java.awt.button; Which of the following statements is false (D)

A, Button belongs to java.awt package B, Button in java.awt directory

C, Button in java.awt file

D. Button belongs to the class of Sun

13. Classes defined by abstract (D)

A. Can be instantiated

B. Cannot subclass

C, cannot be inherited

D. can only be inherited

14. Continue statement (C)

A. Interrupt only the innermost loop

B. Interrupt only the outermost loop

C, interrupt only the next cycle in the cycle of the layer

D. Only interrupt the loop at a certain level

15. Each program that uses a component must have a (B)

A, button

B, container

C, menus,

D, labels,

16. In a user-defined subclass of a Java Applet, it is usually necessary to override the (D) method of the parent class to perform some drawing operations.

A. start( )

B. stop( )

C. init( )

D. paint( )

Second, the judgment question

1. For the container javax.swing.jPanel, its default layout is BorderLayout. The default layout in the (×) JPanel is FlowLayout

2. Sockets, also known as sockets, are used to describe IP addresses and ports. (fx)

3. Threads have a priority between 1 and 10, and the lower the number, the more urgent the task. (x)

The priority of the thread is represented by an integer between 1 and 10. The higher the value, the higher the priority, that is, the faster the execution. The default priority is 5.

4.Java language classes only allow single inheritance. (fx)

5. The Java source program has the extension.java, and the compiled program has the extension.class. (fx)

6. Resources that can only be accessed by one thread at a time are called critical resources. Code that accesses critical resources is called critical code. (x)

Data shared between multiple threads is called a critical resource

7. Concurrency is when events and tasks start at the same time. (×) (parallelism is the beginning of the same moment)

8. URLs are unique in the network. (√) (A URL must uniquely and permanently represent an online object)

3. Fill in the blanks

1. The Java language uses a variety of mechanisms to ensure portability, the most important of which is ___Java Virtual Machine ___.

2. The format of the package declaration is __package name. Package name. Package name… ; .

3. When linking is delayed until run-time implementation, the process is called _ dynamic linking _____.

4. Using the default byte character corresponding table, ___getBytes() is the way to convert strings into byte arrays; .

5. In Swing, the class name of a panel with a scroll bar is __jScrollPanel ____.

6. JComboBox is a combination of ____ text box and list box.

7. In the Java language, random access to files can be implemented using the ___RandomAccessFile___ class.

8.Java program can use pure Java ___JDBC_____ driver, and the database connection.

9. Which of the following statements is not true? (B)

The A.JButton is in the javax.Swing package

B. actionevcent in the java.awt package (actually in the javax.Swing package)

C.actionListener is in the java.awt.event package

The d.ont class is in the java.awt package

10. Which of the following streams does not belong to a byte stream (D)?

A.FileInputStream B.BufferedInputStream C.FileInputStream D.InputStreamReader

4. Short answer questions

1. Write the function of the init() method in the Applet class.

The init() method: It does some initialization for the Applet to work properly.

2. Write out the two steps to place the components in the empty layout.

1) Set the container layout to a NULL layout using the SetLayout (NULL) statement.

2) Then call the setBounds(int x, int y, int width,int height) method to set the size and position of the component in pixels in the container.

3. In Swing, how many types of dialog boxes are there? Please write down the main differences between them.

Five: file dialog box, message dialog box, input dialog box, confirmation dialog box, color dialog box

Different functions are called depending on the implementation

4. Please write down the main work of implementing multithreading with Runnable interface. (Note the upper and lower case class names and variable names.)

public class MyRunnable implements Runnable{ public void run(){ for(int i = 0; i<10000; i++){ System.out.println("aaaaaaaaaaaaa"); }} public class TestDemo {public static void main (String[] args) {MyRunnable MR = new MyRunnable(); Thread t = new Thread(mr); T.start(); // Thread start}}}

5. Write a program that creates a text file, enters characters from the keyboard into the text file, and ends with END.

Make sure you don’t miss the braces

Public class Demo4 {public static void main(String[] args) {System.out.println(" "); Scanner scanner = new Scanner(System.in); String str = scanner.next(); File f=new File("d:\\ss.txt"); FileOutputStream fos=null; try { fos=new FileOutputStream(f); // Byte [] Bytes =new Byte [1024]; Fos.write (Str.getBytes ()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); }}}}

6. Features of the Java language.

Features of the Java language:

(1) Simple

(2) object-oriented

(3) Distributed

(4) robust

(5) Safe

(6) Architecture-neutral

(7) Portable

(8) Explanatory

7. How do you create a thread in Java?

(1) Create Thread by inheriting Thread class

(2) Create threads by implementing the Runnable interface

(3) Create threads through Callable and Future

8. What are the three elements of event handling?

1) Event Source: the place where the Event occurs, which refers to each component, such as button, etc. Clicking the button is actually an Event that occurs on the component;

2) Event: Event encapsulates the events that happen on the component, such as button click, button release, etc.

3) Event Listener: it is responsible for listening for specific types of events that occur on the Event source, and must be responsible for processing the corresponding events when the events arrive;

9. What’s the difference between abstract classes and interfaces?

(1) Non-abstract methods can exist in abstract classes, and methods in interfaces are abstract methods by default;

(2) When implementing a method of an abstract class, if the method is abstract, the subclass must override the abstract method. If the method is not abstract, the subclass can choose to inherit. If the interface is implemented, the subclass must implement all methods in the interface, because by default all methods in the interface are abstract methods.

(3) An abstract class can have private member variables and member methods. Methods in the interface are all modified by default as methods of type public abstract.

(4) A class can inherit only one abstract class, a class can implement multiple interfaces, interfaces can implement multiple inheritance

(5) Non-abstract methods in abstract classes can choose to inherit, and all methods in the interface must be overridden, and all are public methods.

The original author: Su Xu links: https://blog.csdn.net/weixin_… Source Lcsdn

Supplement the Java technology stack

Java concurrent programming, JVM, data structures and algorithms, network protocols, databases, MySQL, 52 SQL performance optimization strategies, 1000 lines of SQL commands, Redis, MongoDB, Spring, MyBatis, SpringBoot, Spring & SpringBoot common annotations, microservices, Dubbo, Nginx, ZooKeeper, MQ, Kafka, Elasticsearch

algorithm

  1. Find the 10 smallest numbers in a billion.
  2. There are 100 million numbers, and two of them are repeated. Find it quickly, in optimal time and space.
  3. 200 million randomly generated unordered integers to find the middle size value.
  4. For an input string of unknown (possibly large) length, design a scheme to rearrange duplicate characters.
  5. Traverse the binary tree.
  6. There are 3n plus 1 numbers, and 3n of them are repeated, and only one of them is unrepeated. How do you find them?
  7. Write a string (for example: http://www.javastack.cn) to reverse the function.
  8. Commonly used sorting algorithm, fast row, merge, bubble. Optimal time complexity of quicksort, worst time complexity. Bubble sort optimization scheme.
  9. Time complexity of binary search, advantage.
  10. A TreeSet that has already been built, how to do the reverse sorting.
  11. What is a B+ tree, B- tree, lists the actual usage scenarios.
  12. A unidirectional linked list, deletes the penultimate NTH data.
  13. Find the top20 element in 200 ordered arrays with 100 elements in each array.
  14. One way linked list, look for the middle element.

Database knowledge

  1. What are the database isolation levels? What do they mean? What is the default isolation level for MySQL?
  2. What is phantom reading.
  3. What are the storage engines for MySQL, and what are their advantages and disadvantages?
  4. Under high concurrency, how to safely modify the same row data.
  5. What are optimistic locks and pessimistic locks? What are InnoDB’s standard row level locks? Explain what they mean.
  6. What are the general steps of SQL optimization, how to view the execution plan, and how to understand the meaning of each field in it?
  7. How does MySQL solve the deadlock problem?
  8. What are the types of indexes? How to create reasonable indexes? How to optimize indexes?
  9. The difference between clustered and non-clustered indexes.
  10. What does SELECT FOR UPDATE mean, will it lock the table or the row or whatever.
  11. Why Btree implementation, how it splits, when it splits, why it’s balanced.
  12. What is the ACID of a database.
  13. A table has nearly ten million data, CRUD is slow, how to optimize.
  14. Mysql > optimize table scan
  15. How to write SQL to effectively use composite indexes.
  16. The difference between in and exists in MySQL.
  17. Possible problem with increasing primary key of database.
  18. MVCC meaning, how to implement.
  19. Have you ever encountered library and table division in any of your projects? How to do it? Is it useful to middleware, such as Sharding JDBC, etc.? Do you know their principles?
  20. How to solve the MySQL master – slave delay?

The message queue

  1. Usage scenarios for message queues.
  2. Message retransmission, supplemental policy.
  3. How to ensure the order of the message.
  4. What MQ have you used, what are the advantages and disadvantages compared with other MQs, is the connection of MQ thread safe, and what is the MQ service architecture of your company?
  5. How to ensure that the data of MQ system is not lost.
  6. RabbitMQ how to achieve cluster high availability.
  7. The reason for Kafka’s high throughput.
  8. The difference between Kafka and other message queues and how Kafka master-slave synchronization is implemented.
  9. How to achieve final consistency using MQ.
  10. Have you encountered any problems in using Kafka and how to solve them?
  11. MQ may have repeated consumption. How to avoid it and how to achieve idempotency?
  12. How to deal with the delayed message of MQ? Can you set the expiration time of the message? How do you usually deal with the expired message?

The cache

  1. What are the common caching strategies, how to achieve the consistency between caching (such as Redis) and data in DB, what caching system is used in your project, and how to design it?
  2. How to prevent cache breakdown and avalanches.
  3. How updates to cache data after expiration are designed.
  4. Redis List structure related operations.
  5. What are the Redis data structures?
  6. What should you pay attention to when using Redis? Discuss the persistence method, memory Settings, the application and advantages and disadvantages of clustering, and the elimination strategy, etc.
  7. The difference between redis2 and redis3, the internal communication mechanism of redis3.
  8. What are the current Redis Cluster’s gameplay, advantages and disadvantages, and scenarios?
  9. The principle of Memcache, which data fit in the cache.
  10. Memory management differences between Redis and memcached.
  11. How to solve the concurrency competition problem in Redis? Do you know the CAS operation of Redis transactions?
  12. What is the election algorithm and process in Redis?
  13. Redis persistence mechanism, AOF and RDB differences.
  14. How does the Redis cluster synchronize data?
  15. Know which Redis optimizations work.
  16. The principle of master-slave replication mechanism of REIDS.
  17. What is the threading model of Redis?
  18. Consider designing an adaptive local cache that can control the overall size of the cache.
  19. How do you think about the use of caching (local caching, centralized caching)? Explain the advantages and disadvantages of local caching versus centralized caching. Cautions for concurrent use of local cache.

supplement

How to learn Java, share two universal learning databases:

1. Books:

codeGoogler/ProgramBooks

2. Video Tutorials:

SpringBoot, Spring, MyBatis, Redis, RabbitMQ, SpringCloud, High Concurrency (Continuous Updates)

Brush 200 questions to the top of the headlines, I float!

If you feel good, remember to forward your attention, and we will continue to update selected technical articles in the future!

Finally, we continue to use our official account, “Terminal R&D Department”, to recommend a quality technology related article every day, mainly to share JAVA related technology and interview skills. Our goal is to know what it is, why, lay a good foundation, do every point well! This main technology public number is worth everyone’s attention.