Java interview questions sorting "Basic"

What is object orientation?

Object-oriented: Everything in life can be called an object, and everything that can be seen everywhere in life is an object. We can extract and extract the state characteristics (attributes) and behavior characteristics (methods) of these things, and use fixed form of representation.

Object Oriented vs Process Oriented:

Process-oriented focuses more on each step and the order of execution , while object-oriented considers who is involved and what can be done .

Process-oriented splits the task into a series of steps: (take laundry as an example)

  • 1. Turn on the washing machine
  • 2, put clothes
  • 3. Put the washing powder
  • 4. Cleaning
  • 5. Drying

Object-oriented will split the human and washing machine two objects:

  • People: Turn on the washing machine, put clothes, put laundry detergent
  • Washing machine: washing, drying

In terms of results: procedure-oriented performance is higher than object-oriented. Because class calls need to be instantiated, the overhead is relatively large, and resources are consumed, so when performance is the most important consideration , process-oriented development is generally adopted. However, procedure-oriented is not as easy to maintain, reuse, and extend as object-oriented . Because object-oriented has the characteristics of encapsulation, inheritance, and polymorphism, it is possible to design a low-coupling system, making the system more flexible and easier to maintain. However, object-oriented performance is lower than procedure-oriented.

Encapsulation, Inheritance and Polymorphism

Encapsulation:
Encapsulation refers to hiding the state information (attributes) of an object and does not allow external objects to directly access the internal information of the object. But it is possible to provide some methods that can be accessed by the outside world to manipulate properties. Through encapsulation, all member function items that are allowed to be used externally are clearly identified, and its internal details are transparent to external calls, and external callers do not need to care about its specific internal implementation.

inherit:

  • When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, then multiple classes do not need to define these attributes and behaviors, but only need to inherit the single class. Multiple classes can be called subclasses, and a single class is called a parent or superclass.
  • Inheritance is a technique of creating a new class using the definition of an existing class as the basis. The definition of a new class can add new properties or methods (extend the parent class), or have the properties and methods of the parent class, and pass its own The method again implements the method of the parent class (overriding). By using inheritance, new classes can be created quickly, which can improve code reuse, program maintainability, save a lot of time for creating new classes, and improve our development efficiency.
  • Java only supports single inheritance, not multiple inheritance. A class can only have one parent class, not multiple parent classes. Java supports multiple layers of inheritance (inheritance hierarchy). Java inherits the non-private member variables and member methods of the parent class, but please note: the subclass cannot inherit the constructor of the parent class.

Polymorphism:

  • Polymorphism: Multiple forms of a thing (the premise of polymorphism: inheritance, rewriting, upcasting), such as objects of different classes, will produce different execution results when calling the methods of their common parent class.
  • Polymorphism can improve code reusability and reduce coupling between modules. (Overloading and overriding of methods in Java are 2 ways to achieve polymorphism.)

What is the difference between overloading and overriding?

  • Overloading: Multiple methods with the same method name and different parameters are defined in the same class. These methods can be processed differently according to different input data.
  • Overriding: When an instance method inherited by a subclass from the parent class cannot meet the functional needs of the subclass, the instance method needs to be reimplemented in the subclass. This process is called overriding, also known as overriding, overwriting .

Overloaded in the same class, the method name is the same, the parameters are different (the number, order, and type of the parameters are different), and the method return value and access modifier can be different.
The premise of method rewriting: inheritance, requires that the method name, parameter list, and return value type must be the same, the modifier of the subclass is greater than or equal to the parent class, and the thrown exception range is less than or equal to the parent class.

Overridden return value type If the return type of the method is void and primitive data type, the return value cannot be modified when overridden. However, if the return value of the method is a reference type, it is possible to return a subclass of the reference type when overriding.

Constructors cannot be overridden, but can be overloaded, and multiple constructors can appear in a class


What are the characteristics of Java language?

1. Object Oriented

Object-Oriented (OOP) is the foundation of the Java language and an important feature of the Java language. Object-oriented concept: everything in life can be called an object, and things that can be seen everywhere in life are an object. We can extract and extract the state characteristics (attributes) and behavior characteristics (methods) of these things, and represented in a fixed form.

2. Simple and easy to use

The Java language is evolved from C and C++. It omits all the incomprehensible and confusing features (such as pointers) in the C language, and becomes more rigorous, concise, and easy to use.

3. Robustness

Java's security check mechanism kills many program errors in the blue. In addition, the Java language also has many features to ensure program stability and robustness (strong type mechanism, exception handling, automatic garbage collection, etc.), which effectively reduces errors and makes Java applications more robust.

4. Security

Java is usually used in the network environment, for this reason, Java provides a security mechanism to prevent malicious code attacks, which can improve the security of the system.

5. Platform independence

The Java platform independence is realized by the Java virtual machine, and Java software can run normally in any computer environment without being constrained by computer hardware and operating system.

6. Support multi-threading

There is no built-in multi-threading mechanism in the C++ language, so the multi-threading function of the operating system must be invoked for multi-threaded programming, while the Java language provides multi-threading support. The multi-threading mechanism enables the application program to execute multiple tasks in parallel at the same time, which enables the program to have better interactivity and real-time performance.

7. Distributed (support network programming)

The Java language has powerful and easy-to-use network capabilities and is very suitable for developing distributed computing programs. Java provides a network application programming interface (java.net), which enables us to remotely access objects through URL, Socket, etc.

8. Compilation and interpretation coexist

Java is a language where compilation and interpretation coexist


JDK 、JRE和JVM

insert image description here

JDK: Abbreviation for Java Development Kit, java development kit, is a product of Sun Microsystems for Java developers, provides a java development environment and runtime environment, JDK contains JRE, you can find a jre directory in the JDK installation directory .

JRE: Short for Java Runtime Environment, it is an indispensable runtime environment for running programs written in the Java language. Through it, Java developers are able to release their own programs to users, allowing users to use them. There are bin and lib folders in the jre file. We can think that the bin folder corresponds to the JVM, and lib corresponds to the class library required for the JVM to work.

JVM: java virtual machine for short, is the java virtual machine we often say, it is the core part of the entire java to achieve cross-platform, all java programs will first be compiled into .class class files (bytecode files), Such class files can be executed on a virtual machine. The JVM shields the information related to the specific operating system platform, so that the Java program only needs to generate the object code (bytecode) running on the Java virtual machine, and it can run on various platforms without modification.

You need to run java programs, just install JRE, you
need to write java programs, you need to install JDK

Bytecode file:
A bytecode file is a file (file extension .class) that can be run on the JVM, it is not oriented to any specific processor, only to the virtual machine. The Java language solves the problem of low execution efficiency of traditional interpreted languages ​​to a certain extent by means of bytecodes, and at the same time retains the portability of interpreted languages. Therefore, Java programs are more efficient to run, and because bytecodes are not specific to a specific machine, Java programs can be run on computers with different operating systems without recompiling.


Know the new features of JDK8?

  • Lambda expressions: allow functions as parameters of a method (functions are passed into methods as parameters.
  • Stream stream: functional programming, stream computing
  • Default method: A default method is a method that has an implementation in an interface.
  • Method references: Method references provide a very useful syntax for directly referencing methods or constructors of existing Java classes or objects (instances). Used in conjunction with lambdas, method references can make language constructs more compact and concise, reducing redundant code.

What is the difference between String, StringBuffer and StringBuilder?

Variability:

String class uses the final keyword to modify the character array to save the string, so the String object is immutable, and each operation will generate a new object. Both StringBuilder and StringBuffer inherit from the AbstractStringBuilder class. In AbstractStringBuilder, a character array is also used to save the string char[]value but it is not modified with the final keyword, so both objects are mutable.

Thread safety:

The objects in String are immutable, which can be understood as constants and thread-safe. The constructors of StringBuilder and StringBuffer are implemented by calling the parent class constructor, namely AbstractStringBuilder (which defines some basic operations on strings and is thread-safe). StringBuffer synchronizes the method or synchronizes the calling method, so it is thread-safe. StringBuilder does not synchronize methods, so it is not thread-safe.

performance:

Every time the String type is changed, a new String object is generated, and then the pointer points to the new String object. Instead of generating a new object and changing the object reference, StringBuffer operates on the StringBuffer object itself every time. In the same situation, using StringBuilder can only get about 10%~15% performance improvement compared to using StringBuffer, but it takes the risk of multi-threading insecurity.

A summary of the use of the three:
1. Operating a small amount of data: suitable for String
2. Operating a large amount of data in a single-threaded string buffer: Applicable to StringBuilder
3. Operating a large amount of data in a multi-threaded string buffer : for StringBuffer

Why is String immutable?

What is the difference between an interface and an abstract class?

Abstract class: If there is an abstract method in a class, then this class can only be an abstract class. There can be no abstract method in an abstract class. An abstract method can only be declared and cannot be implemented.

Interface: In Java, an interface is a specification, a more abstract abstract class. Need to be implemented by the class.

The difference between the two:

  • A class can implement multiple interfaces, but only one abstract class. The interface itself can also be extended by inheriting from the interface.
  • Only public static constants can be defined in the interface, no other variables can be defined, methods are public by default, and all methods cannot have implementations in the interface (the interface methods can have default implementations since Java 8); abstract classes can be defined Ordinary variables and abstract methods need to be implemented. They cannot be static or private. They can be modified with public , protected and default modifiers.
  • All abstract methods in an abstract class must be implemented by the subclass. If the subclass cannot implement all the abstract methods of the parent class, then the subclass can only be an abstract class. Similarly, when an interface is implemented, if it cannot implement all the interface methods, then the class can only be an abstract class.
  • From the design level, abstraction is the abstraction of class, which is a kind of template design (is-a), while interface is the abstraction of behavior, and it is a specification of behavior (like-a).

Same point:

Neither abstract classes nor interfaces can be directly instantiated. To instantiate them, the abstract class variable must point to a subclass object that implements all abstract methods, and the interface variable must point to a class object that implements all interface methods.


What is the difference between member variable and local variable?

  1. From a grammatical point of view: member variables belong to classes, while local variables are variables defined in methods or parameters of methods; member variables can be modified by modifiers such as public , private , and static , while local variables cannot Modified by access control modifiers and static; however, member variables and local variables can be modified by final.
  2. Judging from the way variables are stored in memory: if the member variable is modified with static, then the member variable belongs to the class, and if it is not modified 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 to the constant pool.
  3. From the perspective of the lifetime of variables in memory: member variables are part of the object, which exist with the creation of the object, while local variables disappear automatically with the method invocation.
  4. If a member variable is not assigned an initial value: it will be automatically assigned the default value of the type (an exception: a member variable modified by final must also be explicitly assigned a value), while local variables will not be automatically assigned.

What is the difference between == and equals?

  • ==: To compare whether two objects are equal, the essence is to compare whether the values ​​of the two are equal. For basic data types, the ==comparison is the value. For reference data types, the ==comparison is the memory address of the object (because the value stored in the reference type variable is the address of the object).
  • equals() : Its function cannot be used to judge variables of basic data types, but can only be used to judge whether two objects are equal. But it generally has two use cases:
    • Case 1: The class does not override the equals() method. Then comparing two objects of this class by equals() is equivalent to comparing the two objects by "==".
    • Case 2: The class overrides the equals() method. Typically, we override the equals() method to compare the contents of two objects for equality; if their contents are equal, return true (ie, consider the two objects equal).

Take String as an example:
The equals method in String is overridden, because the equals method of object compares the memory address of the object, while the equals method of String compares the value of the object. When creating an object of type String, the virtual machine looks in the constant pool for an existing object with the same value as the one to be created, and if so, assigns it to the current reference. If not, recreate a String object in the constant pool.
insert image description hereexample:
insert image description here


hashCode 与 equals

Introduction to hashCode():

  • What hashCode() does is get the hash code, also known as the hash code; it actually returns an int. The role of this hash code is to determine the index position of the object in the hash table. hashCode() is defined in JDK's Object.java, which means that any class in Java contains the hashCode() function. The hashcode method of Object is a native method, which is implemented in C language or C++. This method is usually used to convert the memory address of the object to an integer and return it.
  • The hash table stores key-value pairs, and its characteristic is that the corresponding "value" can be quickly retrieved according to the "key". This is where hash codes are used! (you can quickly find what you need)

Why have hashCode?

  • Take "How HashSet checks for duplicates" as an example to illustrate why there is a hashCode?
    When an object is added to a HashSet, the HashSet will first calculate the hashcode value of the object to determine where the object is added, and will also compare it with the hashcode values ​​of other objects that have been added. If there is no matching hashcode, HashSet will assume that the object does not have recurs. But if objects with the same hashcode value are found, the equals() method will be called to check whether objects with equal hashcodes are really the same. If the two are the same, the HashSet will not let its join operation succeed. If it is different, it will be rehashed elsewhere. In this way, we greatly reduce the number of equals, and correspondingly greatly improve the execution speed.

Why must the hashCode method be overridden when overriding equals?

  • If two objects are equal, the hashcode must also be the same.
  • If two objects are equal, calling the equals method on both objects returns true.
  • However, two objects with the same hashcode value are not necessarily equal.
  • Therefore, if the equals method is overridden, the hashCode method must also be overridden.
  • The default behavior of hashCode() is to produce unique values ​​for objects on the heap. If hashCode() is not overridden, then two objects of that class will not be equal in any way (even if the two objects point to the same data)

Why two objects with the same hashcode value are not necessarily equal?

  • Because the hashing algorithm used by hashCode() may happen to return the same hash value for multiple objects. The worse the hash algorithm is, the easier it is to collide, but this is also related to the characteristics of the data range distribution (the so-called collision means that different objects get the same hashCode).
  • We also mentioned HashSet just now. If HashSet has multiple objects with the same hashcode when comparing, it will use equals() to determine whether it is really the same. That is to say, the hashcode is only used to reduce the search cost.

final keyword

The final keyword, which means final, unmodifiable, and the most unchangeable, is used to modify classes, methods and variables, and has the following characteristics:

  • Modified classes: classes cannot be inherited, and all member methods in final classes will be implicitly designated as final methods;
  • Modifier variable: The variable is a constant. If it is a variable of basic data type, its value cannot be changed once it is initialized; if it is a variable of reference type, it cannot be allowed to point to another object after it is initialized .
  • Modifier Methods: Methods cannot be overridden
    Note: Final methods are used for two reasons. The first reason is to lock the method to prevent any inherited classes from changing its meaning; the second reason is efficiency. In earlier Java implementations, final methods were turned into inline calls. But if the method is too large, you may not see any performance gain from inlining calls (now Java versions don't need to use final methods for these optimizations). All private methods in a class are implicitly final.

    insert image description here

What is the difference between final, finally, finalize?

Final can modify classes, variables, methods, modified classes cannot be inherited, modified variables cannot be reassigned, and modified methods cannot be overridden

Finally is generally used in the try-catch code block. The statement in the finally code block will be executed regardless of whether an exception occurs, which is often used to close some streams. (You can use System.exit(int) in a try or finally block to exit the program so that finally does not execute)

finalize: A method of the Object class. Java allows the use of the finalize() method to do the necessary cleanup work before the garbage collector clears the object from memory.


What are the reference types in java?

strong, soft, weak, weak

  • Strong Reference: The most traditional definition of "reference" refers to the ubiquitous reference assignment in program code, that is, a “object obj=new Object()”reference relationship similar to this. In any case, as long as the strong reference relationship exists, the garbage collector will never reclaim the referenced object.
  • Soft Reference (SoftReference): Before the system will overflow memory, these objects will be included in the recycling range for the second recycling. If there is not enough memory after this collection, a memory outflow exception will be thrown.
  • Weak Reference (WeakReference): Objects associated with weak references can only survive until the next garbage collection. When the garbage collector works, objects associated with weak references are reclaimed regardless of whether there is enough memory space.
  • PhantomReference: Whether an object has a virtual reference will not affect its lifetime at all, and it is impossible to obtain a pair of objects through a virtual reference.

How many ways to instantiate an object?

  • new an object: the most common way User user = new User();.
  • Through reflection: call the constructor to initialize
    the newInstance() method of the object Class: User user = User.class.newInstance();, because only the null parameter constructor can be called, the permission must be public.
    Constructor's newInstance(Xxx) method: Constructor<User> constructor = User.class.getInstance(); User user = constructor.newInstance();can call empty parameters, or constructors with parameters
  • Use the clone() method of the object to return the object: User user2 = <User>user.clone();without calling any constructor, copy the existing data directly to initialize the newly created object. Requires that the current class needs to implement the clone interface in the Cloneable interface
  • Use deserialization method: ObjectInputStream in = new ObjectInputStream (new FileInputStream(filename)); User user = (User)obj.readObject();, serialization is generally used for Socket network transmission
  • Create objects through third-party libraries, such as Objenesis

What is reflection?

The JAVA reflection mechanism is the ability to self-observe in the running state. All attributes and methods in a class can be obtained through methods such as class, constructor, field, and method; for any object, any method and attribute of it can be called; The information obtained dynamically and the function of dynamically calling the method of the object is called the reflection mechanism of the java language.

Advantages and disadvantages of reflection mechanism:

  • Advantages: Run-time type judgment, dynamic loading of classes, and improved code flexibility.
  • Disadvantages: Performance bottleneck: Reflection is equivalent to a series of interpretation operations, informing the JVM of what to do, and the performance is much slower than direct java code.

Exception Architecture in Java

insert image description here
In Java, all exceptions have a common ancestor, the Throwable class in the java.lang package. The Throwable class has two important subclasses Exception and Error.

What is the difference between Error and Exception?

Errors of the Exception class can be caught and handled in the application, and such errors are usually encountered and should be handled so that the application can continue to operate normally. Exception can be divided into checked exceptions (must be handled) and unchecked exceptions (may not be handled).

Errors are unhandled (and can only be avoided if possible). This type of error is usually a virtual machine-related error, such as: Java virtual machine operation error ( Virtual MachineError ), virtual machine memory is not enough error ( OutOfMemoryError ) and so on. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread, which cannot be recovered by the application itself;

Checked Exception vs Unchecked Exception

Checked exception:
During the compilation process of Java code, if the checked exception is not handled by catch/throw, the program will fail to compile. For example, the following IO operation code. Except for RuntimeException and its subclasses, other Exception classes and their subclasses are checked exceptions. Common
checked exceptions are: IO related exceptions, ClassNotFoundException , SQLException (database related exception), etc.

Unchecked exceptions:
During the compilation process of Java code, we can compile normally even if we do not handle unchecked exceptions. Unchecked exceptions often occur in the process of program running, which will cause the execution of the current thread to fail.

Both RuntimeException and its subclasses are collectively referred to as unchecked exceptions, for example:

  • NullPointExecrption (null pointer exception)
  • NumberFormatException (string converted to number)
  • ArrayIndexOutOfBoundsException (array out of bounds)
  • ClassCastException (type cast error)
  • ArithmeticException (arithmetic error) etc.

Our custom exceptions often inherit RuntimeException.

What is the difference between throw and throws?

In addition to catching and handling exceptions, exception handling in Java also includes declaring exceptions and throwing exceptions. The exception to be thrown by the method can be declared on the method through the throws keyword (there may be exceptions, and multiple exceptions may be thrown. exception), or throw an exception object by throwing inside the method (which will definitely throw an exception).


What are the types of IO streams in Java?

  • According to the flow direction of the flow, it can be divided into input flow and output flow;
  • According to the operation unit, it can be divided into byte stream and character stream;
  • According to the role 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 they are actually very regular and closely related to each other. The more than 40 classes of the Java IO stream are all from the following 4 The abstract class is derived from the base class.

  • InputStream/Reader: The base class for all input streams, the former is a byte input stream and the latter is a character input stream.
  • OutputStream/Writer: The base class for all output streams, the former is a byte output stream and the latter is a character output stream.

Structural diagrams classified by operation mode:
insert image description here

Since there is a byte stream, why should there be a character stream?
The character stream is obtained by converting bytes by the Java virtual machine. The problem is that this process is still very time-consuming, and if we don't know the encoding type, we can It is easy to have garbled problems. Therefore, the I/O stream simply provides an interface to directly manipulate characters, which is convenient for us to perform stream operations on characters. If audio files, pictures and other media files use byte streams, it is better to use character streams if characters are involved.


What is serialization? What is deserialization?

If we need to persist Java objects, such as saving Java objects in files, or transmitting Java objects over the network, serialization is required in these scenarios.

  • Serialization: The process of converting a data structure or object into a stream of binary bytes
  • Deserialization: The process of converting the binary byte stream generated in the serialization process into a data structure or object

What is the difference between BIO, NIO and AIO?

BIO: Synchronous blocking, the reading and writing of data must be blocked in a thread to wait for its completion. Its characteristics are that the mode is simple and easy to use, and it does not need to consider too many problems such as system overload and current limit. For the case where the number of connections is not particularly high, this model is still relatively good. However, the concurrent processing capability of this model is low. Whenever a client initiates a request to the server, the server has to start a thread, which is powerless when faced with tens or even millions of connections.

NIO: Synchronous and non-blocking, it is an upgrade of B IO. It supports buffer-oriented, Channel-based I/O operations and realizes multiplexing. NIO supports both blocking and non-blocking modes. The blocking mode is the same as the traditional support, which is relatively simple, but the performance and reliability are not good; the non-blocking mode is just the opposite. For low-load, low-concurrency applications, synchronous blocking I/O can be used to improve development speed and better maintainability; for high-load, high-concurrency (network) applications, NIO's Blocking mode to develop

AIO: Asynchronous and non-blocking, it is an upgrade of NIO, also called NIO2. Asynchronous IO is implemented based on events and callback mechanisms, that is, the application will return directly after the operation and will not be blocked there. When the background processing is completed, the operating system The corresponding thread will be notified for subsequent operations. The request sent by the client is first handed over to the operating system for processing, and the OS notifies the thread after processing.


deep copy vs shallow copy

  • Shallow copy: copy the value of the data directly for the basic data type, copy the reference address of the object for the reference data type, the new and old objects point to the same memory address, modify the value of one object, and the value of the other object will follow Change.
  • Deep copy: copy the value of the data directly for the basic data type, open up a new memory space for the reference data type, copy an identical object in the new memory space, the new and old objects do not share memory, modify the value of one of the objects , does not affect the other object.

Deep copies are slower and more expensive than shallow copies.


Reference article:
https://gitee.com/SnailClimb/JavaGuide
https://www.bilibili.com/video/BV1Eb4y1R7zd
https://csp1999.blog.csdn.net/article/details/117168128

Guess you like

Origin blog.csdn.net/Lzy410992/article/details/119302825