Summary record of Java interview questions (1) - basic articles

1. Features of the Java language

(1) It is easy to learn and has a rich class library.
(2) Object-oriented (the most important feature of Java, which makes the program less coupled and more cohesive)
(3) Platform-independent (JVM is the foundation of java cross-platform use)
(4) Reliable and safe
(5) Support multi-threading


2. The difference between object-oriented and process-oriented

  • Process-oriented: It is to analyze and solve the steps of the problem, and then use functions to realize these steps one by one, and then call them one by one when using them. The performance is high, so single-chip microcomputers, embedded development, etc. generally adopt process-oriented development.
  • Object-oriented: It is to decompose the transaction that constitutes the problem into various objects, and the purpose of establishing an object is not to complete each step, but to describe the behavior of a thing in the process of solving the entire problem. Object-oriented has the characteristics of encapsulation, inheritance, and polymorphism , so it is easy to maintain, reuse, and expand. A low-coupling system can be designed, but the performance is worse than process-oriented.

3. Eight basic data types, sizes, and encapsulation classes

basic data type size (bytes) Defaults Package class
byte 1 0 Byte
short 2 0 Short
int 4 0 Integer
long 8 0 Long
float 4 0.0f Float
double 8 0.0 Double
char 2 \u0000(null) Character
boolean - false Boolean

Notice:

(1) Differences between basic data types and reference data types:

Int is the basic data type , and Integer is the encapsulation class of int , which belongs to the reference data type . The default value of int is 0, and the default value of Integer is null, so Integer can distinguish between 0 and null. When Java detects null, it knows that the reference does not point to an object. An object must be specified before the reference, otherwise an error will be reported.

(2) Reasons for the phenomenon of passing by reference after an array object is assigned to another array object:

The system will automatically allocate space when the basic data type is declared, while the reference data type is only allocated a reference space when it is declared, and must be instantiated to open up the data space before it can be assigned. The assignment of an array object is also to copy its own address to another array object to the reference space, so the phenomenon of passing by reference occurs.

(3) Characteristics of boolean data type in Java

Although Java defines the boolean data type, it only provides very limited support for it. There is no bytecode instruction for boolean in the JVM. The boolean value operated by the Java language expression is replaced by the int value of the JVM after compilation, and the boolean array will be encoded into a byte array of the JVM. Each boolean element occupies 8 bits (1 byte). In this way, we can conclude that the boolean type is 4 bytes (int) when used alone, and 1 byte when used in an array. byte (byte). The reason for using int is that for a 32-bit CPU, the data processed at a time is 32 bits, which has the characteristics of efficient access.


4. Naming rules for identifiers

  • The meaning of the identifier: refers to the program, custom content, such as class name, method name, variable name, etc. are all identifiers.
  • Naming rules (required): ① Identifiers can contain English, arrays, underscores, and dollar signs. ② Do not start with a number. ③ Identifiers cannot be keywords.
  • Naming specification (not required): class name specification: the first character of each word is capitalized (upper case); variable name specification: the first character is lowercase, and the first character of other words is uppercase (lower case mode); method name specification: the same as the variable name specification.

5. The role of the instanceof keyword

  • What is instanceof?
    interfaceof is strictly a binary operator in Java that tests whether an object is an instance of a class.
  • How to use interfaceof?
boolean reasult = obj instanceofClass;

Where obj is an object, and Class represents a class or interface. When obj is an object of Class, or a direct or indirect subclass, or an implementation class of an interface, the result reasult will return true, otherwise it will return false.

Note: The compiler will check whether obj can be converted to the class type on the right. If it cannot be converted, an error will be reported directly. If the type cannot be determined, it will be compiled, depending on the operation.

int i = 0;
//编译不通过,说明int不能直接转换为Integer
i instanceof Integer; 
//编译不通过,因为int是基本数据类型,并不是引用数据类型
i instanceof Object; 
Integer integer = new Integer(1);
//编译通过,说明integer能直接转换为Integer
integer instanceof Integer; //true
//编译通过,因为integer是引用数据类型,引用数据类型就是一个对象,是Object类的子类。
integer instanceof Object; //true

Scenario where the return value is false: The intstanceof operator stipulated in the JavaSE specification is: if obj is null, return false.

null instanceof Object; //false

6. Java's automatic boxing and unboxing

  • Boxing: Automatically convert basic data types to wrapper types (int -> Integer); call Integer.valueOf(int)implementation.
  • Unboxing: Automatically convert the wrapper type to the basic data type (Integer -> int); call Integer.intValue()the implementation.

Before Java SE5, if you want to generate an Integer object with a value of 10, you must use the new keyword to instantiate the Integer object.

Integer i = new Integer(10);

Since Java SE5, the feature of autoboxing has been provided. If you want to generate an Integer object with a value of 10, you can directly use assignment to generate it.

Integer i = 10;

Related written test questions:

(1) What will the following code output?

public class Main{
	public static void main(String[] args){
		Integer i1 = 100;
		Integer i2 = 100;
		Integer i3 = 200;
		Integer i4 = 200;
		
		System.out.println(i1 == i2);
		System.out.println(i3 == i4);
	}
}

operation result

true
false

Reason: The objects referenced by i1 and i2 are the same, but the objects referenced by i3 and i4 are different.

Integer.valueOf source implementation

When the value of the parameter i is within [-128, 127], it will return a reference to an existing object in IntegerCache.cache; otherwise, create a new Integer object.

public static Integer valueOf(int i) {
    
    
	if (i >= IntegerCache.low && i <= IntegerCache.high)
		return IntegerCache.cache[i + (-IntegerCache.low)];
	return new Integer(i);
}

(2) What will the following code output?

public class Main{
	public static void main(String[] args){
		Double i1 = 100.0;
		Double i2 = 100.0;
		Double i3 = 200.0;
		Double i4 = 200.0;
		
		System.out.println(i1 == i2);
		System.out.println(i3 == i4);
	}
}

operation result

false
false

Double.valueOf source implementation

Double will instantiate a Double object regardless of the number of arguments.

    public static Double valueOf(double d) {
    
    
        return new Double(d);
    }

7. The difference between overloading and rewriting

(1) Override

Literally, rewriting means "rewriting it all over again". In fact, the subclass rewrites the method of the parent class.

The subclass inherits the original method of the parent class, but sometimes the subclass wants to modify the method of the parent class, so the method is modified or rewritten when the method name, parameter list, and return type (except that the return value of the subclass method is a subclass of the return value of the parent class method) are the same.

When rewriting, it should be noted that the access authority of the subclass function cannot be lower than that of the parent class.

public class Father {
    
    
    public static void main(String[] args) {
    
    
        Son son = new Son();
        son.sayHello();
    }

    public void sayHello(){
    
    
        System.out.println("Hello");
    }
}

class Son extends Father{
    
    
    @Override
    public void sayHello() {
    
    
        System.out.println("hello by son");
    }
}

Summarize:

  • Overloading occurs between parent class and child class
  • The method, parameter list, and return type (the return value of the parent class method and the child class method must be the same or have an inheritance relationship) must be the same
  • Subclass method access rights must be the same or greater than the parent class
  • The overridden method must not throw a new Exception or use a wider Exception (such as throwing Exception directly)

(2) Overload

In a class, methods with the same name that have different parameter lists (different types, numbers, and orders) are considered overloaded.

public class Father {
    
    
	 public static void main(String[] args) {
    
    
		 Father f = new Father();
		 f.sayHello();
		 f.sayHello("wintershii");
	 }
	 
	 //同名方法1
	 public void sayHello() {
    
    
	 	System.out.println("Hello");
	 }

	 //同名方法2
	 public void sayHello(String name) {
    
    
	 	System.out.println("Hello" + " " + name);
	 }
}

Summarize:

  • Overloading Overload is a polymorphic expression in a class
  • Overloading requires different parameter lists for methods with the same name
  • Overloaded methods can change the return value, and do not judge whether it is overloaded by the return value

8. equals and ==

(1)“==”

"==" compares the object memory address in the variable (stack) memory to determine whether it is the same object.

Compare to:

  • The comparison is whether the two ends of the operator are the same object
  • Objects on both sides must be of the same type to compile
  • The address is compared. If the comparison is made with a specific number, the comparison is made with the content (the number is placed in the static constant pool)

(2)equals

equals compares whether the contents of two objects are equal.

Since all classes inherit from the Object class, if the subclass does not override the equals method, call Object.equals(), and Object internally uses "==" for comparison.

Summary: When all comparisons are equal, use equals and when comparing constants, use the constant.equals(xxx) specification for comparison (because when using Object's equals, the object may be a null pointer).


9. The function of Hashcode

There are two types of collections in Java

  • List: ordered and repeatable
  • Set: unordered and not repeated

(1) How can the set be checked for duplicates?

Through the equals method, it is not suitable for high-volume Set collections, so the hash algorithm is used to improve the efficiency of finding elements in the collection.

(2) Hash algorithm

This method divides the collection into several storage areas. Each object can calculate a hash code and group the hash codes. Each group corresponds to a storage area. According to the hash code of an object, the area where the object should be stored can be determined.

(3) hashCode method

hashCode is a value converted from the memory address of the object.

When adding a new element to the collection, first call the hashCode method of this element to obtain the hash code, and then check whether there is an element in the Hash storage area. If there is no element at this location, it will be directly stored at this location without any further comparison; if there is an element, call the equals method for comparison, and if it is not the same, hash other addresses.


10. The difference between String, String StringBuffer and StringBuilder

(1)String

String is a read-only string and is a reference data type.

From the perspective of the underlying source code, it is a character array of final type , and the referenced string cannot be changed (because final is locked), and once defined, it cannot be modified.

Every time an operation is performed on String, a new String object will be produced.

private final char[] value;

(2) "+" operator of String

Each "+" operation will create a new StringBuilder object on the heap that is the same as the original string, and then call the append() method to splice new characters.

(3)StringBuffer和StringBuilder

Both inherit the AbstractStringBuilder abstract class, the bottom layer of the abstract class is a variable character group.

Action suggestion

  • When performing frequent string operations, it is recommended to use StringBuffer and StringBuilder for operations.
  • StringBuffer is thread-safe: add a synchronization lock to the method or add a synchronization lock to the called method .
  • StringBuilder is thread-unsafe: there is no synchronization lock on the method .

11. The difference between ArrayList and linkedList


(1) Array: Index-based data structure

  • Advantages: fast search and read data, the time complexity of Array to get data is O(1)
  • shortcoming:
    • Array initialization must specify the length, otherwise the compilation will fail
    • The overhead of deletion is huge (subsequent data needs to be migrated)

(2) List: It is an ordered collection that can contain repeated elements, provides index access, and inherits from Collection

Two implementation classes

  • ArrayList: an array that can be automatically expanded (the bottom layer is Array, which is realized by array expansion)
    • toArray(): returns an array (Array)
    • asList(): returns a list (List)
  • LinkedList: A doubly linked list, in the operation of a large amount of data, it is more suitable for adding and deleting elements than ArrayList (characteristics of linked lists), but weaker than ArrayList (characteristics of arrays) in Get/Set .

12. The difference between HashMap and HashTable

1. The parent classes of the two are different

(1) Differences

  • HashMap: Inherit the AbstractMap class
  • HashTable: Inherit the Dictionary class

(2) The same point: the three interfaces of Map , Cloneable (reproducible) and Serializable (serializable) are realized .

2. The interfaces provided to the outside world are different

(1) HashTable provides more elements() and contains() two methods.

  • elements(): Inherited from Dictionnary , used to return the enumeration of values ​​in this HashTable .
  • contains(): Determine whether the HashTable contains the specified value. ( containsValue() modifies contains() )

3. Different support for null

  • Hashtable: Neither key nor value can be null.
  • HashMap:
    • key can be null , but unique (maintain the principle of uniqueness of key )
    • value can be null and unlimited.

4. Different security

  • HashMap is not thread-safe . In a multi-threaded concurrent environment, problems such as deadlock may occur.
  • HashTable is thread-safe , and each method has a synchronized (synchronization lock) keyword, so it can be directly used in multi-threading.

Although HashMap is not thread-safe, its efficiency is much higher than that of HashTable . This design is reasonable, because most usage scenarios are single-threaded. When multi-threaded operations are required, thread-safe ConcurrentHashMap can be used , which is more efficient than HashTable (because ConcurrentHashMap uses segment locks and does not lock the entire data).

5. The initial capacity is different from the capacity of each expansion

The initial length of HashTable is 11, and the initial length of the original 2n+1
HashMap is 16, and each expansion is 2n

6. The method of calculating the hash value is different

HashTable directly uses the hash value of the object.
In order to improve the calculation efficiency, HashMap fixes the size of the hash table to the power of 2, so that in the modulo calculation, it does not need to do division, but only needs to do bit operation. (more efficient)


13. The difference between Collection package structure and Collections

(1) Collection is the upper-level interface of the collection class, and its sub-interfaces include Set, List, LinkedList, ArrayList, Vector (dynamic array), and Stack (stack).

(2) Collections is a tool class of the collection class, which contains various static polymorphic methods related to collection operations, which are used to implement operations such as searching, sorting, and thread safety on various collections. It serves the Java Collection framework and cannot be instantiated.


14. The four references of Java, strong and weak

(1) Strong reference: One of the most commonly used reference methods, when the program memory (OOM) is insufficient, it will not be recycled.

String str = new String("str");
System.out.println(str);

(2) Weak reference: JVM recycles when found.

WeakReference<String> wrf = new WeakReference<String>(str);

Available scenarios: The key in java.util.WeakHashMap in the Java source code uses weak references. Once a reference is not needed, the JVM will automatically handle it, and the user does not need to do other operations.

(3) Soft reference: When the program memory (OOM) is insufficient, it will be recycled.

// 注意:wrf这个引用也是强引用,它是指向SoftReference这个对象的,
// 这里的软引用指的是指向new String("str")的引用,也就是SoftReference类中T
SoftReference<String> wrf = new SoftReference<String>(new String("str"));

Available scenarios: When the cache is created, the created object is put into the cache, and when the memory is insufficient, the JVM recycles the object.

(4) Virtual reference:

The recycling mechanism of phantom references is similar to that of weak references. They are put into the ReferenceQueue before recycling , while other references are passed into the ReferenceQueue after being recycled by the JVM .

Due to this mechanism, phantom references are mostly used for processing before the reference is destroyed . When creating a phantom reference, it must have a ReferenceQueue .

PhantomReference<String> prf = new PhantomReference<String>(new String("str"),
new ReferenceQueue<>());

Available scenarios: some operations before object destruction, such as resource release, etc. Although Object.finalize() can also do this
kind of action, this method is both unsafe and inefficient.

Note: These types of references are all references to the object itself, not to the references of the four subclasses of Reference (SoftReference, etc.).


15. Generic common features

(1) The concept of generics

Generics are a feature since Java SE 1.5. The definition of generics in "Java Core Technology" is“泛型” 意味着编写的代码可以被不同类型的对象所重用。

(2) Characteristics of generics

We provide a general concept, but there can be specific rules to constrain it.

Take the creation of ArrayList<Integer> as an example

List<Integer> list = new ArrayList<>();

(3) Advantages of generics

  • Numeric types that do not require a fixed future parameter
  • Freedom to constrain required types via rules
  • Generics are also subclasses of Object

16. Several ways to create Java objects

(1) New creates a new object (through the constructor)
(2) Through the reflection mechanism (through Class.newInstance())
(3) Using the clone mechanism (by implementing the Cloneable interface, rewriting the clone method, and cloning a new object through the existing object and the method is the same as the property) (4) Through the serialization mechanism (the serialized object can be obtained after deserialization
)


17. Is it possible that two unequal objects have the same hashcode

It is possible that when a hash conflict occurs, two unequal objects will have the same hashcode value.

solution:

(1) Zipper method: each hash node has a next pointer, and multiple hash nodes can build a one-way linked list through the next pointer, and objects with the same hashcode will be hung on this linked list. (Set's duplicate checking mechanism)

(2) Open addressing method: Once a conflict occurs, it will be hashed to the next empty address. As long as the hash table is large enough, it can always be found and stored. (The hash table solution in the data structure class)

(3) Rehashing: It is also called double hashing method, and there are multiple hash functions. When a conflict occurs, different calculation hashcodes are used until there is no conflict.


18. What is the difference between deep copy and shallow copy?

  • Shallow copy: refers to the variables of the new object and the original object are the same, but the reference object of the new object and the original object is the same, but a pointer is added to point to the existing memory address.
  • Deep copy: refers to the variables of the new object and the original object are the same, but the reference object of the new object and the original object is different, a pointer is added and a new memory is applied for and points to the new memory.

19. What are the uses of final?

The meaning of final is the final meaning, which means that everything it modifies cannot be modified.

Common Answers:

(1) The final modified class cannot be inherited
(2) The final modified method cannot be rewritten
(3) The final modified variable cannot be modified. If the object is modified, the reference address remains unchanged and the reference content is variable (
4) The final modified method, the JVM will try to inline to improve efficiency
(5) The final modified constant is stored in the constant pool during the compilation phase

Additional answer:

The editor must follow two reordering rules for the final field (rearrange the order of execution) :

  • The writing of final in the constructor and the assignment of object references , these two operations cannot be reordered
  • The initial reading of an object reference containing a final and the subsequent initial reading of the final cannot be reordered

20. What are the uses of static?

  • Static Variables: Shared Variables
  • Static Methods: Generic Methods
  • Static code block: mostly used for initialization operations
  • Static inner class: modify static class
  • Static import package: use import static , is a feature introduced in JDK1.5, used to specify the import of static resources in a class.
import static java.lang.Math.*

public class Main{
    
    
	public static void main(String[] args]{
    
    
		System.out.println(random());
	}
}

21. What is the return value of 3*0.1 == 0.3

program execution result

false

Result analysis

The "==" operator is used to compare whether the objects on the left and right sides are the same. Obviously, floating-point numbers will have insufficient precision. 3*0.1 = 0.300000000000000004, which is the result of CPU execution. Since the values ​​are directly compared to see if they are equal, it is false.


22. Is there any difference between a=a+b and a+=b?

The execution process is consistent, but compilation exceptions may occur in the final output.

a = a + b: the execution process is to assign the result of a + b to a, and when the result exceeds the range of the assignment type, a mutation error will occur java: 不兼容的类型: 从int转换到byte可能会有损失
a += b: the execution process is a+b and then assigned to a, but implicit automatic type conversion will be performed (the calculation result will be converted to a larger type if it exceeds the type range).

Derivative question

//下列代码是否有错
short s = 1;
s = s + 1;

wrong. When short is calculated, it will be automatically promoted to int type, then the result of s+1 is int type, and s is short type, so the compilation fails. If s += 1 is used, it is correct.


23. Try catch finally, there is return in try, is finally still executed?

Execute, and execute finally earlier than return.

in conclusion:

  • No matter what happens in the finally code block, it will be executed (after the return expression is calculated, it will be stored, and after the finally code block is executed, the calculation result will be returned)
  • It is best not to put return in the finally code block, otherwise the program will exit early

24. Excption and Error package structure

There are three types of throwable structures in Java: checked exceptions , runtime exceptions , and errors

(1)CheckedException

Definition: The Exception class itself and its subclasses, all exceptions except RuntimeException are checked exceptions.

Features: The Java compiler will check it, and can declare and throw it through throws, or catch it through try-catch, otherwise it will not compile.

(2)RuntimeException

Definition: RuntimeException and its subclasses are called runtime exceptions.

Features: The Java compiler does not catch this exception. For example, the divisor is zero exception, the array out-of-bounds exception, and the exception generated by the fail-fast mechanism (fail-fast is a fast failure mechanism, which is an error detection mechanism for a Java collection. When multiple threads make structural changes to the collection, it is possible to generate a fail-fast mechanism ) .

Common five RuntimeException

  • ClassCastException (class conversion exception)
  • IndexOutOfBoundsException (array out of bounds)
  • NullPointerException (null pointer exception)
  • ArrayStoreException (data storage exception, the operation array is inconsistent in type)
  • BufferOverflowException (buffer area overflow exception)

(3)Error

Definition: Error class and its subclasses.

Features: Like runtime exceptions, the compiler does not check for errors.

Errors occur when resources are insufficient, constraints fail, or other conditions occur that prevent the program from continuing.

The program itself cannot fix these errors. For example, VirtualMachineError, OutOfMemoryError, and ThreadDeath are errors, and the occurrence of such errors will cause the program to terminate.

Java virtual machine specification: The memory of the JVM is divided into several blocks, such as heap, stack, program counter, method area, etc.


25. What situations have you encountered in OOM, and what situations have you encountered in SOF

(1)OOM

OOM is the abbreviation of OutOfMemoryError. In addition to the program counter, several other runtime areas of the virtual machine memory may have OOM exceptions.

  • Java Heap 溢出:java.lang.OutOfMemoryError:Java heap spacess

The Java heap is used to store object instances. As long as objects are created continuously and there is a reachable path between GC Roots and objects to avoid the garbage collection mechanism from clearing these objects, OOM exceptions will occur when the number of objects reaches the maximum heap capacity limit.

To resolve this exception:

Use a memory image analysis tool (such as Eclipse Memory Analyzer) to analyze the heap dump snapshot from the dump. The focus is to confirm whether the objects in the memory are necessary. First, distinguish whether it is due to a memory leak (Memory Leak) or a memory overflow (Memory Overflow). If there are no leaks, check that the virtual machine parameters (-Xmx and -Xms) are set appropriately.

  • Virtual machine stack and native method stack overflow

If the stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine, a StackOverflowError exception will be thrown.

If the virtual machine cannot apply for enough memory space when expanding the stack, an OutOfMemoryError exception will be thrown

It should be noted here that when the stack is larger, the number of threads that can be allocated is smaller.

  • Runtime constant pool overflow

Exception information: java.lang.OutOfMemoryError: PermGenspace

If you want to add content to the runtime constant pool, the easiest way is to use the Native method String.intern().

The function of this method is: if the pool already contains a string equal to this String, return the String object representing this string in the pool; otherwise, add the string contained in this String object to the constant pool, and return the reference of this String object.

Since the constant pool is allocated in the method area, we can limit the size of the method area through -XX:PermSize and -XX:MaxPermSize, thereby indirectly limiting the capacity of the constant pool.

  • Method area overflow
    The method area is used to store Class-related information, such as class name, access modifier, constant pool, field description, method description, etc. or the class object saved in the method area has not been recycled in time or the memory occupied by the class information exceeds our configuration.

Exception information: java.lang.OutOfMemoryError: PermGenspace

Method area overflow is also a common memory overflow exception. If a class is to be reclaimed by the garbage collector, the judgment conditions are very strict
. Pay special attention to this point in applications that often dynamically generate a large number of Classes.

(2)SOF

Definition of StackOverflowError : This error is thrown when the application recurses too deeply and a stack overflow occurs.

Because the stack is generally 1-2mb by default, once an infinite loop or a large number of recursive calls occurs, the stack capacity will exceed 1mb during the continuous push process, resulting in
overflow.

Reasons for stack overflow: recursive calls , a large number of loops or infinite loops , whether there are too many global variables , and the data of arrays, lists, and maps is too large .


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

(1) Thread:

  • A unit of execution that is smaller than a process.
  • A process can spawn multiple threads during execution.
  • Multiple threads of the same type share the same memory space and a set of system resources, so when the system generates a thread or switches between threads, the burden is smaller than that of the process, and the thread is also called a lightweight process.

(2) Program

  • Files containing instructions and data are stored on disk or other data storage devices, which means that programs are static codes.

(3) process

  • It is an execution process of a program and the basic unit for the system to run a program, so the process is dynamic.
  • The steps for the system to run a program are the process of a process being created, running, and dying. A process is an executing program, which executes one instruction after another in the computer. At the same time, each process also occupies system resources such as CPU time, memory space, files, IO device usage rights, and so on.

The relationship between threads, programs, and processes

  • process creates thread
  • thread service program
  • program creation process

27. What should I do if some fields do not want to be serialized in Java serialization?

Keyword: transient

Function: prevent serialization of variables modified with this keyword in the instance; when the object is deserialized, variables modified by transient will not be persisted and restored.

Restrictions: Only variables can be modified.


28. Talk about the IO stream in Java

(1) Classification of IO streams

  • According to the flow direction: input flow and output flow
  • Divided by operating unit: byte stream and character stream
  • According to the role of flow: node flow and processing flow

(2) 4 base classes of IO stream

  • InputStream/Reader: The base class of all input streams, the former is a byte input stream, and the latter is a 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

(3) Classified according to the mode of operation:

  • Reader
    • Node streams: FileReader, PipedReader, CharArrayReader
    • Handling streams: BufferedReader, InputStreamReader
  • Writer
    • Node streams: FileWriter, PipedWriter, CharArrayWriter
    • Handling streams: BufferedWriter, InputStreamWriter, PointWriter
  • InputStream
    • Node streams: FileInputStream, PipedInputStream, ByteArrayInputStream
    • Handling streams: BufferedInputStream, ObjectInputStream, SequenceInputStream
  • OutputStream
    • Node streams: FileOutputStream, PipedOutputStream, ByteArrayOutputStream
    • Processing streams: BufferedOutputStream, DataOutputStream, ObjectOutputStream, PrintStream

(4) Classified according to the operation object:

  • File operations: FileInputStream, FileOutputStream, FileReader, FileWriter
  • Buffered operations: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter
  • Pipeline operations: PipedInputStream, PipedOutputStream, PipedReader, PipedWriter
  • Basic data type operations: DataInputStream, DataOutputStream
  • Object serialization: ObjectInputStream, ObjectOutputStream
  • Conversion control: InputStreamReader, OutputStreamWriter
  • Print control: PrintStream, PrintWriter
  • Array operations: ByteInputStream, ByteOutputStream, CharArrayReader, CharArrayWriter

29. The difference between Java IO and NIO

NIO, namely New IO, this library is introduced by JDK1.4. NIO has the same function and purpose as IO, but the implementation method is different.

NIO mainly uses blocks, so NIO is more efficient than IO.

Two sets of NIO are provided in the Java API

  • Standard output: IO
  • Network output: NIO

30. The working principle of java reflection

(1) Definition: The reflection mechanism is that at runtime, 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. In Java, as long as the name of the class is given, all the information of the class can be obtained through the reflection mechanism.

(2) Java reflection mechanism usage scenarios

Class.forName("com.mysql.jdbc.Driver.class"); #加载MySQL驱动类

In fact, frameworks such as Hibernate and struts are also implemented through reflection mechanisms.

(3) Implementation of reflection

Step 1: Get the Class object

  • Class.forName("path name of the class")
  • classname.class (method of Object)
  • object.getClass()
  • The wrapper class of the basic type, you can call the Type property to get the Class object

(4) Classes that implement java reflection

  • Class: Represents classes and interfaces in a running Java application. It should be noted that all object information is implemented through the Class class.
  • Filed: Provides attribute information about classes and interfaces, and dynamic access to it.
  • Constructor: Provides information about a single constructor of a class and its access rights
  • Method: Provides information about a method in a class or interface

(5) Advantages and disadvantages of reflection mechanism

  • advantage
    • Ability to dynamically obtain instances of classes at runtime, improving flexibility
    • combined with dynamic compilation
  • shortcoming
    • The performance of using reflection is low, and the bytecode needs to be parsed to parse the objects in memory.
    • Relatively unsafe and destroys encapsulation.

(6) Solutions to the shortcomings of the reflection mechanism

  • Through setAccessible(true), turn off the JDK security check to improve the reflection speed
  • When an instance of a class is frequently used, there is a cache
  • Use the ReflectASM tool class to speed up reflection through bytecode generation

31. Tell me about the difference between List, Set, and Map?

  • List (a good helper to deal with order): The List interface stores a set of ordered and repeatable objects
  • Set (focus on unique properties): The Set interface stores a set of unordered and non-repeated objects.
  • Map (experts to search with Key): use key-value pair storage. Map will maintain the value associated with the key, and the key is unique, and the value can be repeated.

32. What common methods does Object have? Roughly talk about the meaning of each method

  • clone method: a shallow copy method, this method can only be called if the Cloneable interface is implemented, otherwise an exception is thrown that clone does not support, does deep copy also need to implement the clone interface, and at the same time, the class that references the variable implements the clone interface and overrides the clone method
    .
  • finalize method
    This method is related to the garbage collector. The last step for the JVM to determine whether an object can be recycled is to determine whether this method has been rewritten.
  • equals method
    This method is used frequently, and the custom comparison method is generally rewritten in subclasses.
  • hashCode method
    This method is used to calculate the hash value. Rewriting the equals method generally requires rewriting the hashCode method. This method is used in some Collections with hash functions.
    Generally satisfied obj1.equals(obj2)==true, it can be introduced obj1.hashCode()==obj2.hashCode(), but the hashCode equality does not necessarily satisfy equals, so for efficiency, the above two conditions are usually close to equivalent.
    JDK 1.6, 1.7 returns random numbers by default.
    JDK 1.8 defaults to a random number obtained by running Marsaglia's xorshift scheme random number algorithm through a random number related to the current thread + three certain values.
  • The wait method
    is used in conjunction with synchronized . The wait method is to make the current thread wait for the lock of the object. The current thread must be the owner of the object, that is, it has the lock of the object. The wait() method waits until the lock is acquired or is interrupted. wait(long timeout) sets a time interval, and returns if the lock is not acquired within the specified time.
    After calling, the current thread goes to sleep until the time happens:
    • Other threads call notify()
    • Other threads call notifyAll()
    • Other threads call interrupt to interrupt the thread and throw interruptedException
    • time interval is up
  • The notify method
    is used in conjunction with synchronized to wake up a thread in the waiting queue on the object (the thread in the synchronization queue is for the thread that preempts the CPU, and the thread in the waiting queue refers to the thread waiting to wake up)
  • The notifyAll method
    is used in conjunction with synchronized , which wakes up all threads waiting in the queue on this object.

Summarize:

Other methods include toString() and getClass methods.


33. How many ways are there to create objects in Java?

  • keyword new
User user = new User();
  • Reflection
User user = User.class.newInstance();
Object obj = (Object)Class.forName(User.class).newInstance();
  • clone method
#默认User 实现了Cloneable且重写了clone方法
User user = new User();
User clone = user.clone();
  • Create objects using deserialization
#默认对象实现了Serializeable接口
Object obj = ObjectInputStream.readObject();

34. What are the ways to obtain a Class object?

  • getClass()
User user = new User();
user.getClass();
  • static member class
User.class
  • forName()
Class.forName(User.class)

35. Have you ever used ArrayList? Tell me what are its characteristics?

ArrayList has some features other than the basic expandable features and array features.

  • add(o) , add to the end of the array, if the amount of added data is large, you should use ensureCapacity(), the function of this method is to set the size in advance, which can greatly improve the initialization speed.
  • add(int, o) , adding to a certain point, may move a large number of array elements, and may trigger the expansion mechanism.

In the case of high concurrency, threads are not safe. When multiple threads operate ArrayList at the same time, unpredictable exceptions or errors will occur.

ArrayList implements the Cloneable interface, indicating that it can be copied. NOTE: This clone is a shallow clone.


36. Why make an ArrayList when there are arrays?

ArrayList not only has the efficiency of arrays, but also has the expansion mechanism of List. When the amount of data is not clear, it can store data without initializing the space.


37. Tell me what is fail-fast?

The fail-fast mechanism is an error mechanism of Java collections. When multiple threads operate on the contents of the same collection, fail-fast events may be generated.

For example: when a thread A traverses the collection through an iterator, if the content of the collection is changed by other threads, when thread A accesses the collection, a ConcurrentModificationException will be thrown and a fails-fast event will be generated. The operations here mainly refer to add, remove and clear to modify the number of collection elements.

Solution: Use the classes under the java.util.concurrent package to replace the classes under the java.utils package.

It can be understood as follows: before traversing, record modCount as expectModCount, and then compare expectModCount with modCount. If they are not equal, it proves that they have been modified concurrently, and a ConcurrentModificationException is thrown


38. Key in HashMap Can we use any class as key?

HashMao's key is mostly of String type. When we want to use a custom class as a key, we need to pay attention to the following points:

  • If the class overrides equals(), also override hashCode()
  • All instances of the class need to follow the rules related to equals and hashCode
  • If a class does not use equals, it should not be used in hashCode
  • It is best to make the custom key immutable, so that the HashCode can be cached and have better performance.

39. Why is the length of HashMap 2 to the Nth power?

In order to increase the efficiency of HashMap accessing data, reduce hash value conflicts as much as possible, try to distribute data evenly, and make each linked list or red-black tree as equal in length as possible.

The important reason for the problem: the remainder ( %) operator, if it is a power of 2, is equivalent to the AND ( &) operator minus one from its divisor (that is, hash % length == hash &(length - 1)the premise is that the length is 2 to the nth power), and it uses binary bit operations, &which %can improve operational efficiency.


40. Similarities and differences between HashMap and ConcurrentHashMap

  • (1) They are all stored in the form of key-value
  • (2) HashMap is thread-unsafe, and ConcurrentHashMap is thread-safe under JUC
  • (3) The bottom layer of HashMap is array + linked list (before JDK 1.8), after JDK1.8, it is array + linked list + red-black tree. When the number of elements in the linked list reaches 8, the query speed of the linked list is slower than that of the red-black tree, and the linked list will turn into a red-black tree.
  • (4) The initial array size of HashMap is 16 (default), and when expansion occurs, the expansion factor is 0.75 for expansion.
  • (5) Before JDK1.8, ConcurrentHashMap used segment locks to implement Segment (segment lock) + HashEntry, and the size of the Segment array defaulted to 16, 2 to the nth power; after JDK1.8, Node + CAS (lock-free strategy) + Synchronized was used to ensure concurrent security.

41. What are the characteristics of red-black trees?

red black tree

  • Each node is black or red
  • root node is black
  • Each leaf node is black
  • If a leaf node is red, its child nodes must be black
  • All paths from a node to its descendants contain the same number of black nodes

42. Tell me how you usually handle Java exceptions

try-catch-finally

  • try : Responsible for monitoring code
  • catche : responsible for catching exceptions and handling them
  • finally : Responsible for releasing resources, regardless of any exceptions or return results

custom exception

By inheriting java.lang.Exceptionthe class, if you want to customize RuntimeExceptionit java.lang.RuntimeException, implement a no-argument construction and a parameter construction method with string parameters.

In the business code, it can be captured by custom targeted exceptions, such as user authorization verification, etc...

Guess you like

Origin blog.csdn.net/Zain_horse/article/details/131819246