Prepare for gold three silver four! Arrangement of java job interview questions for first-line Internet companies: Java basics + multithreading + collection + JVM collection!

Preface

Looking back at 2020, it is really the fastest year that I have ever experienced. It is really fast passing by. I have finished boasting in the coming year before reflecting on it. I believe everyone has already started to work! As the saying goes, the new year and the new atmosphere are about to be the most important gold three and silver four of the year. I have been asked by fans to sort out some interview questions for java posts before. There was no time a year ago. This time I will take advantage of the New Year's Day. I have sorted out some Java job interview questions for first-line Internet companies, mainly Java basics + multithreading + collection + JVM, full of dry goods are placed below! There is a lot of content, you can choose the part you need to watch!

What are the characteristics of the Java language?

  • Easy to learn;
  • Face-oriented objects (encapsulation, inheritance, polymorphism);
  • Platform independence (Java virtual machine realizes platform independence);
  • reliability;
  • safety;
  • Support multi-threading (C++ language does not have a built-in multi-threading mechanism, so the multi-threading function of the operating system must be invoked
    to design multi- threaded programming, while Java language provides multi-thread support);

The difference between the orientation object and the orientation process

  • Orientation process: The performance of the orientation process is higher than that of the orientation object. Because the class needs to be instantiated when it is called, the overhead is less than that of the resource, so when performance is the most important consideration, it is used like a stand-alone machine, embedded development, Linux/Unix, etc. Face to process development. However, the orientation process is not easy to maintain, easy to reuse, and easy to extend.
  • Face objects: face objects are easy to maintain, easy to reuse, and easy to expand. Because face objects have the characteristics of encapsulation, inheritance, and polymorphism, a low-coupling system can be designed to make the system more flexible and easier to maintain. However, the performance of the direction object is lower than the direction process.

What is a java virtual machine

  • The Java Virtual Machine (JVM) is a virtual machine that runs Java bytecode. JVM has specific implementations for different systems (Windows, Linux, macOS), but they all give the same results if they use the same bytecode.

What is bytecode? What are the benefits of using bytecode?

  • In Java, the code that the JVM can understand is called bytecode (that is, a file with a .class extension), which is not directed to any specific processor, but only to the virtual machine. The Java language uses bytecode to solve the problem of low execution efficiency of traditional interpreted languages ​​to a certain extent, while retaining the portability of interpreted languages. Therefore, the Java program is highly effective when running. Moreover, because the bytecode is not specific to a specific machine, the Java program can be run on a variety of computers with different operating systems without recompilation.

About JVM and bytecode

  • The Java Virtual Machine (JVM) is a virtual machine that runs Java bytecode. JVM has specific implementations for different systems (Windows, Linux, macOS), but they all give the same results if they use the same bytecode. Bytecode and JVM implementation of different systems are the key to the Java language "compile once, run anywhere".

JDK 和 JRE

  • JDK is the Java Development Kit, which is a full-featured Java SDK. It has everything that JRE has, as well as a compiler (javac) and tools (such as javadoc and jdb). It can create and compile programs.
  • JRE is the Java runtime environment. It is a collection of everything needed to run a compiled Java program, including the Java Virtual Machine (JVM), Java class libraries, java commands, and some other basic components. However, it cannot be used to create new programs.

Contrast between Oracle JDK and OpenJDK

  • Oracle JDK releases a major version every 6 months, while the OpenJDK version releases a major version every three months. But this is not fixed, I think it is useless to understand this.
  • OpenJDK is a reference model and is completely open source, while Oracle JDK is an implementation of OpenJDK, not completely open source;
  • Oracle JDK is more stable than OpenJDK. The code of OpenJDK and Oracle JDK are almost the same, but Oracle JDK has more classes and some bug fixes. Therefore, if you want to develop enterprise/commercial software, I suggest you choose Oracle JDK because it has been thoroughly tested and stable. In some cases, some people mentioned that they may encounter many application crashes when using OpenJDK, but just switch to Oracle JDK to solve the problem;
  • In terms of responsiveness and JVM performance, Oracle JDK and OpenJDK provide better performance;
  • Oracle JDK will not provide long-term support for the upcoming version, and users must obtain the latest version by updating to the latest version to obtain support each time;
  • Oracle JDK is licensed under the binary code license agreement, while OpenJDK is licensed under the GPL v2 license.

What is the main class of a Java program. What is the difference between the main class of the application and the main class of the subprogram?

  • There can be multiple classes in a program, but only one class can be the main class. In a Java application, this main class refers to the class containing the main() method. In a Java program, this main class is a subclass that inherits the self-system class JApplet or Applet. The main class of the application may not necessarily be a public class, but the main class of the application must be a public class. The main class is the point where the Java program is executed.

What are the differences between Java applications and subprograms?

  • Simply put, the application is started from the main thread (that is, the main() method). There is no main() method for applet subprograms. They are mainly embedded in the browser and run (call init() or run() to start). Embedding into the browser is similar to flash games.

What is the difference between character constants and string constants?

  • Formally: A character constant is one character enclosed in single quotation marks; a string constant is several characters enclosed in double quotation marks
  • Meaning: A character constant is equivalent to an integer value (ASCII value) and can participate in expression operations; a character string constant represents an address value (the string is stored in the memory location)
  • Occupies a large amount of memory. Character constants only take up 2 bytes; string constants take up as many bytes (note: char occupies two bytes in Java)

Can Constructor be overridden?

  • Constructor cannot be overridden, but it can be overloaded, so you can see that there are multiple constructors in a class.

The difference between overloading and rewriting

  • Overloading is the same method that can make different processing according to the input data
  • Rewriting is when the subclass inherits the same method of the self class, and the input data is the same, but when you want to make a different response from the class, you have to override the method of the class

Talk about the three characteristics of Java object programming: encapsulation inheritance polymorphism

Package

  • Encapsulation privatizes the properties of an object, and at the same time provides methods for properties that can be accessed by the outside world. If the properties do not want to be accessed by the outside world, we do not need to provide methods for outside access. But if a class does not provide access to the outside world, then this class has no meaning.

inherit

  • Inheritance is a technology that uses the definition of an existing class as the basis to build a new class. The definition of a new class can add new data or new functions, and
    can also use the functions of the class, but it cannot selectively inherit the class. By using inheritance, we can easily reuse previous code.

Remember the following 3 points about inheritance:

  • The subclass has all the properties and methods of the class object (including private properties and private methods), but the private properties and
    methods in the subclass are not accessible, but only owned.
  • Subclasses can have their own attributes and methods, that is, subclasses can be extended to subclasses.
  • Subclasses can be implemented in a self-contained way. (Introduced later).

Polymorphism

  • The so-called polymorphism refers to the specific type pointed to by the referenced variable defined in the program and the method call issued through the referenced variable is not determined at the time of programming, but is determined during the running of the program, that is, a referenced variable. Which class instance object the variable will point to, and the method that the variable is used to call, can only be determined during the running of the program. There are two forms of polymorphism that can be achieved in Java: inheritance (rewriting the same method by multiple subclasses) and interface (implementing the interface and overriding the same method in the interface).

Talk about automatic packing and unpacking

  • Packing: Pack the basic types with their corresponding reference types;
  • Unboxing: Convert the packaging type to the basic data type;

Why is it illegal to call a non-static member in a static method?

Since static methods can be called without using objects, in static methods, other non-static variables cannot be called, and members of non-static variables cannot be accessed.

Define a construction method that does nothing and has no parameters in Java

  • Before the Java program executes the subclass construction method, if it does not use super() to call the class-specific construction method, it will call the "parameterless construction method" in the class. Therefore, if only a parameterized construction method is defined in the class, but in the construction method of the subclass, super() is not used to call a specific construction method in the class, an error will occur at compile time , Because the Java program cannot find a construction method without parameters in the class for execution. The solution is to add a construction method that does nothing and has no parameters to the class.

What is the difference between import java and javax?

  • At the beginning, the required packages for JavaAPI were packages starting with java. At that time, javax was only used to extend the API package. However, over time, javax has gradually expanded to become an integral part of the Java API. However, moving the extension from the javax package to the java package is really too cumbersome and will eventually break a bunch of existing code. Therefore, it was finally decided that the javax package would become a part of the standard API. So, there is actually no difference between java and javax. This is all a name.

What is the difference between interface and abstract class?

  • The default connection method is public, and all methods cannot be implemented in the connection (the Java 8 connection method can have a default implementation), but abstract classes can have non-abstract methods.
  • In addition to static and final variables, there can be no other variables in the interface, but not in the abstract class.
  • One class can implement multiple interfaces, but only one abstract class can be implemented. The interface itself can extend
    multiple interfaces through the extends keyword .
  • The default modifier of the access method is public, and the abstract method can have public, protected, and default modifiers (the abstract method is to be rewritten so it cannot be modified with the private keyword!).
  • From the design level, abstraction is the abstraction of classes, a kind of template design, and the connection is the abstraction of the behavior, and it is a norm of behavior.

What are the differences between member variables and local variables?

  1. From the point of view syntax: it belongs to the class member variables, local variables are ⽽ parameter variables defined in the Remedies or methods for the camera; as
    member variables can be modified by public, private, static and other modifiers, local variables ⽽ Cannot be
    modified by access control modifiers and static; however, member variables and local variables can be modified by final.
  2. From the perspective of the storage method of variables in memory: if a member variable is decorated with static, then the member variable belongs
    to the class; if it is not decorated with static, the member variable belongs to the instance. The object is stored in the heap memory. If the local
    variable type is a basic data type, it is stored in the stack memory. If it is a reference data type, it stores a reference to the heap memory
    object or an address in the constant pool.
  3. From the perspective of the storage time of variables in memory: member variables are a part of the object, and they exist with the creation of the object, but local
    variables disappear automatically with the call of the method.
  4. If a member variable has not been assigned an initial value: it will automatically be assigned with the default value of the type (an exception is the case: a final-modified
    member variable must also be explicitly assigned), but local variables will not be assigned automatically.

What operator is used to create an object? What is the difference between object entity and object reference?

  • The new operator, new creates an object instance (the object instance is in the heap memory), and the object reference points to the object instance (the object reference is stored in the stack memory). An object reference can point to 0 or 1 object (a rope can be either not tied to the ball or a ball); an object can have n references to it (n ropes can be used (Sub) tie a ball).

What is the return value of the method? What is the function of the return value in the method of the class?

  • The return value of a method refers to the result of executing the code in a certain method body we obtained! (The premise is that the method may produce results). The function of the return value: Receive the result so that it can be used for other operations!

What is the purpose of the construction method of a class? If a class does not declare the construction method, can the program be executed correctly? Why?

  • The main function is to complete the initialization of the class object. Can be executed. Because even if a class does not declare a construction method, there will be a default
    construction method without parameters.

What are the characteristics of the construction method?

  • The name is the same as the class name.
  • There is no return value, but the constructor cannot be declared with void.
  • It is automatically executed when the object of the class is created, and there is no need to call it.

What is the difference between the static method and the example method

  • When calling a static method externally, you can use the method "class name. method name" or the method "object name. method name".
    The example method is only the latter method. In other words, the static method can be called without creating objects.
  • When accessing the members of this class, static methods are only allowed to access static members (ie, static member variables and static methods), but not
    instance member variables and instance methods; there is no such restriction on instance methods.

What is the difference between the equality of objects and the equality of references to them?

  • The equality of objects is different from whether the contents stored in the memory are equal. If the references are equal, the difference is whether the memory addresses they point to are
    equal.

Before calling the subclass construction method, it will first call the construction method without parameters. What is the purpose?

  • Help the subclass to do initialization work.

Briefly describe the basic concepts of threads, programs, and processes. And what is the relationship between them?

  • A thread is similar to a process, but a thread is a smaller unit of execution than a process. A process can spawn multiple threads during its execution. Different from a process, multiple threads of the same kind share the same memory space and a set of system resources, so when the system produces a thread or switches between threads, the burden is much smaller than the process , And because of this, threads are also called lightweight processes.

  • A program is a file containing instructions and data, which is stored in a disk or other data storage device, which means that the program is static code.

  • The process is the execution process of the program, and the basic unit of the system to run the program, so the process is dynamic. The system running a program is the process of a process from creation, operation to death. Simply put, a process is an executing program. It executes one instruction after another in the computer. At the same time, each process also occupies certain system resources such as CPU time and memory space. Files, access to input and output devices, etc. In other words, when the program is executing, it will be loaded into memory by the operating system. A thread is a smaller unit of operation into which a process is divided. The most important difference between threads and processes is that basically each process is unique, but each thread is not fixed, because threads in the same process are likely to affect each other. From another point of view, the process belongs to the category of the operating system, mainly in the same period of time, can execute more than one program at the same time, and the thread is almost executed at the same time in the same program. The program segment.

Some conclusions about final keywords

  • The final keyword is mainly used in three places: variables, methods, and classes.
  • For a final variable, if it is a variable of a basic data type, its value cannot be changed once it is initialized; if it is a variable of a reference type, it cannot be made to point to another object after its initialization .
  • When a class is decorated with final, it indicates that this class cannot be inherited. All member methods in the final class will be implicitly designated as final methods.
  • There are two reasons for using the final method. The first reason is to lock the method in case any inherited classes modify its meaning; the second reason is efficiency. In the early Java implementation version, the final method will be converted to inline calling. However, if the method is too large, you may not see any performance improvement brought by in-line calling (the current Java version no longer needs to use the final method for these optimizations). All private methods in the class are implicitly designated as final.

Exception handling in Java

Java exception class hierarchy diagram

  • In Java, all exceptions have a common ancestor of the Throwable class in the java.lang package. Throwable: There are two important subclasses: Exception and Error, both of which are important subclasses of Java exception handling, and each contains a large number of subclasses.
  • Error: An error that cannot be handled by the program, which indicates a serious problem in the running application. Most of the errors are not related to the operations performed by the code writer, and do not indicate problems with the JVM (Java Virtual Machine) when the code is running. For example, a Java virtual machine operation error (Virtual MachineError) will appear when the JVM no longer has the memory resources needed to continue the operation
  • OutOfMemoryError. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses thread termination. These errors indicate that the fault occurred in the virtual machine itself, or occurred when the virtual machine tried to execute the application, such as a Java virtual machine running error (Virtual MachineError), a class definition error (NoClassDefFoundError), etc. These errors are not detectable because they are outside the control and processing capabilities of the application, and most of them are conditions that are not allowed to occur during the operation of the program. For a properly designed application, even if an error does occur, it should not essentially try to deal with the abnormal situation it causes. In Java, errors are described by the subclass of Error.
  • Exception: It is an exception that can be handled by the program itself. The Exception class has an important subclass RuntimeException RuntimeException exceptions are thrown by the Java virtual machine. NullPointerException (the exception is thrown when the variable to be accessed does not reference any object), ArithmeticException (an arithmetic operation exception, when an integer is divided by 0, the exception is thrown), and ArrayIndexOutOfBoundsException (subscript out of bounds exception).
  • Note: The difference between exceptions and errors: exceptions can be handled by the program itself, but errors cannot be handled.

Throwable class commonly used method

  • public string getMessage(): returns a brief description when the exception occurred
  • public string toString(): returns detailed information when the exception occurred
  • public string getLocalizedMessage(): Returns the localized information of the abnormal object. Use Throwable's subclass to override this method, and localize the information. If the subclass does not cover this method, the information returned by this method is the same as the result returned by getMessage()
  • public void printStackTrace(): Print the exception information encapsulated by the Throwable object on the console

Exception handling summary

  • try block: used to catch exceptions. It can be followed by zero or more catch blocks. If there is no catch block, it must be followed by a finally block.
  • catch block: used to handle exceptions caught by try.
  • Finally block: Regardless of whether the exception is caught or handled, the statements in the finally block will be executed. When a return statement is encountered in a try block or catch block, the finally block will be executed before the method returns.

In the following 4 special cases, the finally block will not be executed:

  • An exception occurred at the first line of the finally block. Because in other aspects, the finally block will still be executed
  • System.exit(int) is used in the previous code to exit the program. exit is a function with parameters; if the statement is after the exception statement, finally will be executed
  • The thread of the program died.
  • Turn off the CPU.

What if some fields do not want to be serialized in Java serialization?

  • For variables that do not want to be serialized, use transient keyword modification. The purpose of the transient keyword is to prevent the serialization of variables modified by this keyword in the instance; when the object is deserialized, the value of the transient modified variable will not be persisted and restored. transient can only modify variables, not classes and methods.

Get two commonly used methods of keyboard input

Method 1: Via Scanner

Insert picture description here

Method 2: Via BufferedReader

Talk about IO flow in Java

There are several types of IO streams in Java?

  • According to the flow direction of the stream, it can be divided into input stream and output stream;
  • According to the operation unit, it can be divided into byte stream and character stream;
  • According to the color of the flow, it is divided into node flow and processing flow.
    The Java Io stream involves more than 40 classes. These classes look messy, but in fact they are very regular, and they are very closely related to each other. The more than 40 classes in the Java I0 stream are from the following 4 Derived from the abstract base class.
  • InputStream/Reader: The base class of all input streams, the former is byte input stream, and the latter is character input stream.
  • OutputStream/Writer: The base class of all output streams. The former is a byte output stream and the latter is a character output stream.

Classification structure diagram by operation method:

Classification structure diagram by operation object:

Now that there is a byte stream, why is there a character stream?

  • The character stream is obtained by converting the bytes by the Java virtual machine. The problem is that this process is quite time-consuming, and if we don't know the encoding type, it is prone to garbled problems. Therefore, the I/O stream simply provides an interface for directly manipulating characters, so that we usually perform stream operations on characters. It is better to use byte stream for media files such as audio files and pictures, and use character stream if characters are involved.

Talk about deep copying vs. shallow copying

  • Shallow copy: Value transfer for basic data types, and transfer-like copying for reference data types. This is a shallow copy.
  • Deep copy: transfer basic data types by value, create a new object for reference data types, and copy its content, this
    is a deep copy.

Talk about the difference between List, Set and Map?

  • List (good help for order): List access to store a group is not unique (multiple elements can refer to the same object), ordered objects
  • Set (pay attention to the unique nature): Duplicate sets are not allowed. No multiple elements refer to the same object.
  • Map (experts who use Key to search): Use key-value pairs to store. Map will maintain the value associated with Key. Two Keys can refer to the same object, but the Key cannot be repeated. A typical Key is of type String, but it can also be any object.

The difference between HashMap and Hashtable

  • Is thread safe: HashMap is not thread safe, HashTable is thread safe; the internal methods of HashTable are basically modified by synchronized. (If you want to ensure thread safety, use ConcurrentHashMap!);
  • Efficiency: Because of thread safety issues, HashMap is more efficient than HashTable. In addition, HashTable is basically eliminated, do not use it in the code;
  • Support for Null key and Null value: In HashMap, null can be used as a key. There is only one such key, and there can be one or more keys whose corresponding value is null. . However, as long as the key value put in the HashTable has a null value, a NullPointerException is directly thrown.
  • The difference between the initial size and the size of each expansion: ①If the initial value of the capacity is not specified when creating, the default initial size of Hashtable is 11, and after each expansion, the capacity becomes the original 2n+1. The default initialization size of HashMap is 16. After each expansion, the capacity is doubled. ②If the initial value of the capacity is given when creating, then Hashtable will directly use the size you give, and HashMap will expand it to a power of 2 size (the tableSizeFor() in HashMap is guaranteed by the method below) The source code is given). In other words, HashMap always uses the power of 2 as the size of the hash table, and I will introduce why it is a power of 2 later.
  • The underlying data structure: HashMap after JDK1.8 has undergone major changes in resolving hash conflicts. When the length of the linked list is larger than the threshold (the default is 8), the linked list is converted into a red tree to reduce search time. Hashtable has no such mechanism.

What are threads and processes?

What is a process?

  • The process is the execution process of the program, and the basic unit of the system to run the program, so the process is dynamic. The system running a program is the process of a process from creation, operation to death.
  • In Java, when we start the main function, we actually start a JVM process, and the thread where the main function is located is a thread in this process, also called the main thread.

What is a thread?

  • A thread is similar to a process, but a thread is a smaller unit of execution than a process. A process can spawn multiple threads during its execution. Different from a process, multiple threads of the same kind share the process's heap and legal area resources, but each thread has its own program counter, virtual machine stack, and local method stack, so the system is producing a thread, or When switching between threads, the burden is much smaller than the process. Because of this, threads are also called lightweight processes.

Why use multithreading?

  • From the bottom of the computer: A thread can act as a lightweight process, the smallest unit of program execution, and the cost of switching and scheduling between threads is much smaller than that of a process. In addition, the era of multi-core CPU means that multiple threads can run at the same time, which reduces the overhead of thread switching.
  • From the perspective of contemporary Internet development trends: Today's systems require millions or even tens of millions of concurrency at every turn, and multithreaded concurrent programming is the basis for the development of high-concurrent systems. The use of multithreaded mechanisms can greatly improve Concurrency and performance of the overall system

Three important features of concurrent programming

  • Originality: For one operation or multiple operations, either all operations are performed and will not be interrupted by any factor, or all operations are performed or none is performed. synchronized can guarantee the originality of the code segment.
  • Visibility: When a variable modifies a shared variable, other threads can immediately see the latest value after modification. The volatile keyword can ensure the viability of shared variables.
  • Order: the order of code in the execution process, Java's optimization during the compiler and operation, the order of execution of the code may not be the order in which the code is written. The volatile keyword can disable instructions for reordering optimization.

Briefly introduce strong, soft, weak, and false references

强引⽤(StrongReference)

  • In the past, most of the references we used were actually strong references, which is the most common reference. If an object has a strong reference, it is similar to an indispensable utility, and the garbage collector will never collect it. When the memory space is insufficient, the Java virtual machine would rather throw OutOfMemoryError to make the program terminate abnormally, and would not solve the problem of insufficient memory by reclaiming objects with strong references at will.

Soft Reference (SoftReference)

  • If an object only has a soft reference, it is similar to an available utility. If there is enough memory space, the garbage collector will not reclaim it. If the memory space is not enough, it will reclaim the memory of these objects. As long as the garbage collector does not collect it, the object can be used by the program. Soft references can be used to implement memory-sensitive high-speed caches. The soft reference can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the soft reference is garbage collected, the Java virtual machine will add the soft reference to the reference queue associated with it in.

Weak Reference (WeakReference)

  • If an object has only weak references, it is similar to a useful utility. The difference between weak references and soft references is that objects with only weak references have a shorter life cycle. In the process of the garbage collector thread scanning the memory area under its jurisdiction, once an object with only weak references is found, its memory will be reclaimed regardless of the current memory space. However, because the garbage collector is a low-priority thread, it is not certain that objects that only have weak references will be discovered soon. A weak reference can be used in conjunction with a reference queue (ReferenceQueue). If the object referenced by the weak reference is garbage collected, the Java virtual machine will add the weak reference to the reference queue associated with it in.

虚引⽤(PhantomReference)

  • "False reference", as its name implies, is nothing but a fictitious name. It is different from other types of references, and false reference does not determine the life cycle of the object. If
    an object holds only virtual references, then it is the same as without any references and may be garbage collected at any time.

to sum up

Thank you for seeing here, please correct me if there are any deficiencies in the article! Due to the time relationship, I have sorted out so much for the time being. If you have any shortcomings, you can privately message me, and I will follow up and make up. I hope these will be helpful to you in the upcoming golden three silver four!

In addition, I also prepared ava core knowledge points for everyone + a full set of architect learning materials and videos + first-line big factory interview collections + interview resume templates + Alibaba Meituan Netease Tencent Xiaomi iqiyi fast hand Bilibili interview questions + Spring source collection +Share the Java architecture practical e-book for free! Friends in need click here to remark csdn to download by themselves.
If you think the article is helpful to you, remember to give me a thumbs up. You will share java-related technical articles or industry information every day. Welcome everyone to follow and forward the article!

Guess you like

Origin blog.csdn.net/jiagouwgm/article/details/112135228