Directly hit the real interview questions of big factories: JD.com Java intermediate interview questions sharing

1. Under what circumstances will the object be disposed of by the garbage collection mechanism?

Using the reachability analysis algorithm, the virtual machine defines some objects as GC Roots, and starts from the GC Roots and searches down the reference chain. If an object cannot be found through the GC Roots , the virtual machine thinks that the object can be recycled. .

1.1****Which objects can be regarded as **GC ****Roots**?

1) Objects referenced in the virtual machine stack (local variable table in the stack frame);

2) Objects referenced by class static properties in the method area, and objects referenced by constants;

3) The object referenced by JNI (Native method) in the local method stack;

1.2 If the object is unreachable, will it be recycled by the garbage collector?

Even if it is unreachable, the object will not necessarily be collected by the garbage collector,

1) First determine whether it is necessary for the object to execute the finalize() method. The object must override the finalize() method and it has not been run.

2) If it is necessary to execute, the objects will be put into a queue, and the JVM will open a thread to recycle them. This is the last chance for the objects to escape and clean up.

2. Tell me about common coding methods?

The meaning of encoding: the smallest unit stored in the computer is one byte, that is, 8 bits, and the range of characters that can be represented is 255. However, there are too many symbols to be represented by humans, which cannot be fully represented by one byte, so it is necessary to encode the symbols. , which translates various languages ​​into languages ​​that computers can understand.

1) ASCII code: 128 in total, represented by the lower 7 bits of a byte, 0~31 control characters such as carriage return, delete, etc.; 32~126 are printing characters, which can be input and displayed through the keyboard;

2) ISO-8859-1, used to extend ASCII encoding, 256 characters, covering most Western European language characters.

3) GB2312: double-byte encoding, the total encoding range is A1-A7, A1-A9 is the symbol area, including 682 characters, B0-B7 is the Chinese character area, including 6763 Chinese characters;

4) GBK adds more Chinese characters in order to expand GB2312. The coding range is 8140~FEFE, with 23940 code points, which can represent 21003 Chinese characters.

5) UTF-16: ISO is trying to create a new super language dictionary, all languages ​​in the world can be translated to each other through this dictionary Unicode, and UTF-16 defines the access method of Unicode characters in the computer, using two bytes to represent the Unicode conversion format. Any character can be represented by two bytes, namely 16bit, which is called UTF-16.

6) UTF-8: UTF-16 uniformly uses two bytes to represent a character, but some characters can be represented by only one byte, which wastes storage space, while UTF-8 uses a variable-length technology, each coding area There are different character lengths. Different types of characters can consist of 1~6 bytes.

**3 **, **utf-8 ** How many bytes of Chinese in encoding; how many bytes of int type?

utf-8 is a variable-length encoding technology, the bytes occupied by Chinese in utf-8 encoding are uncertain, maybe 2, 3, 4,

The int type occupies 4 bytes.

4. What is the difference between static proxy and dynamic proxy?

Proxy is a common design pattern whose purpose is to provide a proxy for other objects to control access to an object and decouple the relationship between two classes. Both the proxy class and the delegate class implement the same interface, because what the proxy really calls is the method of the delegate class.

Difference :

  1. Static proxy : Created by the programmer or generated by a specific tool, which is a static proxy is determined when the code is compiled. Static proxies usually only proxy one class;
  2. Dynamic proxies : Generates are dynamically created using reflection mechanisms during code execution. The dynamic proxy proxy is multiple implementation classes under an interface;

Implementation steps : a. Implement the InvocationHandler interface to create your own invocation handler; b. Provide the Proxy class with an array of ClassLoader and proxy interface types to create a dynamic proxy class; c. Use the reflection mechanism to obtain the constructor of the dynamic proxy class; d. Use the dynamic proxy The constructor of the class creates a dynamic proxy class object;

Usage scenario: Retrofit directly calls the interface method; Spring's AOP mechanism;

**5 **, Java's exception system

Throwable in Java is the operation class for all exceptions and errors, and the two direct subclasses are Error (error) and Exception (exception):

1) Error is an error that the program cannot handle, generated and thrown by the JVM, such as OOM, ThreadDeath, etc. When these exceptions occur, the JVM typically chooses to terminate the program.

2) Exception is an exception that the program itself can handle, and is divided into runtime exception (RuntimeException) (also called Checked Exception) and non-runtime exception (Unchecked Exception). Runtime exceptions include NullPointerException\IndexOutOfBoundsException, etc. These exceptions are generally caused by program logic errors and should be avoided as much as possible. Non-runtime exceptions include IOException\SQLException\FileNotFoundException and user-defined Exception exceptions.

6. Talk about your understanding of parsing and assignment.

Parsing means that the method is known before running, that is, during compilation, there is a definite version, and it will not change during running. Resolution is static, and symbolic references can be turned into direct references during the resolution phase of class loading.

Dispatching can be divided into static dispatch and dynamic dispatch. Overloading belongs to static dispatch, and override belongs to dynamic dispatch. Static dispatch means that the static type of the parameter is used as the judgment basis instead of the actual type during overloading. During the compilation stage, the compiler can decide which overloaded version to use according to the static type of the parameter. Dynamic dispatch needs to call the corresponding method according to the actual type.

7. Modify the signature of the equals method of object A. When using ****HashMap to store this object instance, which ****equals method will be called?

The equals method of the object will be called. If the equals method of the object is not overridden, the equals method and == both compare the value of the heap memory address pointed to in the local variable table on the stack for equality.

**8 **. What is the mechanism for implementing polymorphism in Java?

Polymorphism means that the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable are not determined at compile time, and it is only determined at runtime which instance of the class a reference variable will point to. This allows reference variables to be bound to various class implementations without modifying the source program. There are three necessary conditions for Java to realize polymorphism: inheritance, reassignment, and upcasting. In polymorphism, the reference of the subclass needs to be assigned to the object of the parent class. Only in this way can the reference be able to call the method of the parent class and the subclass.

9. How to serialize a Java object into a file?

ObjectOutputStream.writeObject() is responsible for writing the specified stream, and ObjectInputStream.readObject() reads serialized data from the specified stream.


//写入try {

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:/student.txt"));

os.writeObject(studentList); os.close();

} catch(FileNotFoundException e) { e.printStackTrace();

} catch(IOException e) { e.printStackTrace();

}
复制代码

10. Tell me about your understanding of Java reflection

In the running state, for any class, you can know all the properties and methods of this class, and for any object, you can call any of its methods and properties. This function of dynamically obtaining information and calling object methods dynamically is called the reflection mechanism of java language.

The role of reflection: During the development process, it is often encountered that a member variable, method or property of a certain class is private, or only open to system applications. Here, you can use the reflection mechanism of java to obtain the required information through reflection. Private members or methods.

Get the Class object instance of the class Class clz = Class.forName("com.zhenai.api.Apple");

1) Obtain the Constructor object Constructor according to the Class object instance appConstructor = clz.getConstructor();

2) Use the newInstance method of the Constructor object to obtain the reflection class object Object appleObj = appConstructor.newInstance();

3) Get the Method object of the method Method setPriceMethod = clz.getMethod("setPrice", int.class);

4) Use the invoke method to call the method setPriceMethod.invoke(appleObj, 14);

5) The properties of the Class class can be obtained through getFields(), but private properties cannot be obtained, while getDeclaredFields() can obtain all properties including private properties. Methods with Declared decoration can be reflected to private methods, those without Declared decoration can only be used to reflect public methods, and other such as Annotation\Field\Constructor as well.

11. Talk about your understanding of Java annotations

Annotations are defined by the @interface keyword. The form is similar to that of interfaces, except that there is an @ in front of them.

public @interface TestAnnotation {



}
复制代码

When using @TestAnnotation to refer to, to make the annotation work properly, you also need to use meta-annotation, which is an annotation that can be annotated on the annotation. There are five meta tags @Retention @Documented @Target @Inherited @Repeatable

@Retention indicates the survival time of the annotation. The value of RetentionPolicy.SOURCE annotation is only retained in the source code stage and discarded when the compiler compiles; the RetentionPolicy.CLASS annotation is only retained until the compilation is in progress, and will not be loaded into the JVM . RetentionPolicy.RUNTIME can be left until the program is running, it will be loaded into the JVM, so they can be obtained when the program is running.

Elements in the @Documented annotation are included in the javadoc

@Target defines the application scenarios of annotations, ElementType.FIELD annotates properties; ElementType.LOCAL_VARIABLE can annotate local variables; ElementType.METHOD can annotate methods; ElementType.PACKAGE can annotate a package ElementType.TYPE can annotate a package Type annotations, such as classes, interfaces, enumerations

@Inherited If a superclass is annotated with @Inherited annotations, and its subclasses are not applied by any annotations, the subclasses can inherit the superclass's annotations;

The role of annotations:

  1. Provide information to the compiler: the compiler can use annotations to detect errors and warnings
  2. Compilation stage: software tools can use annotation information to generate code, html documents or do other corresponding processing;
  3. Run phase: When the program is running, you can use annotations to extract code

Annotations are obtained through reflection. You can use the isAnnotationPresent() method of the Class object to determine whether it has applied an annotation, and then obtain the Annotation object through the getAnnotation() method.

12. Talk about the principle of generics and give an example

Generics is to pass the type into a parameter , so that the types that can be used are diversified, so as to achieve decoupling. Java generics appeared after Java1.5. In order to maintain compatibility with previous versions, the erasure method was used to implement generics. Erasing refers to ignoring the type parameter T to a certain extent, and erasing directly from the class where T is located to the parent class of T, such as calling a generic method, passing in the type parameter T into the method, if not doing something similar when declaring public T methodName(T extends Father t){}, Java performs upward type erasure, and directly treats the parameter t as an Object class instead of the T passed in. That is, inside any class and method with generics, it cannot know its own generic parameters, erasure and transformation occur on the boundary, that is, the passed parameters are erased when entering the class or method, but When it came out, it was converted to the T we set. Within a generic class or method, any operation involving a concrete type (ie, a subclass of the erased type) cannot be performed, such as new T(), or T.play() (play is a method of a subclass and not a method of the erased class)

**13 **, Understanding of String in Java

1) The String class is final, so the String class cannot be inherited, and its member methods are also final by default. Once a String object is created, it is fixed, any changes to the String object will not affect the original object, and any related change operations will generate a new String object.

2) The String class stores strings through char arrays, and String redesigns the equals method to compare the values ​​for equality.

String a = "test"; String b = "test"; String c = new String("test");
复制代码

a, b, and literally test all point to the "test" object in the JVM string constant pool, and they point to the same object. The new keyword must produce an object test, which is stored in the heap. So new String("test") produces two objects, c on the stack and test on the heap. In java, there are no two identical string objects at all, so the test in the heap should refer to the test in the string constant pool.

example:

* String str1 = "abc"; ** // * Open up a space in the stack to store the reference str1 * , * str1 ** points to the String in the pool ** Constant "abc" String ** str2 = "def * "; ** / / * Open up a space in the stack to store the reference str2 * , * str2 ** points to the String in the pool ** Constant "def" String ** str3 = str1 * + ** str2;// * Open up a space in the stack to store the reference str3

//str1+str2 returns a new String object "abcdef" through StringBuilder 's last step * toString() * method

* // * A space will be created in the heap to store this object, and the reference str3 points to the new String * object returned by * (str1+str2) * in the heap. * System.out.println(str3 == * "abcdef");// * return false

Because str3 points to an * "abcdef" * object in the heap, and * "abcdef" * is an object in the character pool, the result is false * . * JVM puts String *** str="abc" * objects in the constant pool at compile time, while String ** str3 =str1+str2 ** is only known at runtime , * new ** Objects are also done at runtime.

**14 **. Why is String designed to be immutable?

String constant pool requires String to be immutable. Because String is designed to be immutable, when a String object is created, if the string value already exists in the constant pool, a new object will not be created, but an existing object will be referenced. If the string variable is allowed to change, it will lead to various logic errors, such as changing one object will affect another independent object.

1) String objects can cache hashCode. The immutability of the string ensures the uniqueness of the hash code, so the hashCode of the String can be cached, so that the hash code does not need to be recalculated every time. When comparing strings, hashCode can be compared directly, which improves performance security

2) Security. String is used by many java classes as parameters, such as URI address, file path, string parameter required by reflection mechanism, etc. If the string is variable, it will cause various security risks.


Author: java Li
Yangyong Link: https://juejin.cn/post/7002398964825882631
Source: Rare Earth Nuggets
The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/wdjnb/article/details/124323070