Java Interview - Basics

Article directory

1. What are the three major characteristics of object-oriented?

Encapsulation : Hide the properties and details of some objects , access to data can only be through the interface exposed to the outside world , and provide protection for the data inside the object .

Inheritance : Inheritance means that the subclass inherits the characteristics and behaviors of the parent class , so that the subclass object (instance) has the instance fields and methods of the parent class , or the subclass inherits the methods from the parent class , so that the subclass has the same behavior as the parent class .

Polymorphism : For the same behavior , different subclass objects have different manifestations . There are three conditions for the existence of polymorphism: 1. Inheritance 2. Rewriting 3. The parent class reference points to the subclass method. In layman's terms, it's like playing a game, with the same button, different characters will release different skills .

2. What are the familiar features of Java?

  1. Easy to learn: Java discards vague concepts such as operator overloading and multiple inheritance that are difficult to understand in C++. In particular, the Java language does not use pointers , but uses references , and provides an automatic garbage collection mechanism , so that programmers do not have to worry too much about memory management issues.

  2. Object-oriented: Remember the three characteristics of encapsulation, inheritance, and polymorphism .

  3. Platform independence: Compile once and run everywhere (Write Once, Run any Where), the reason is the support of the Java Virtual Machine (JVM), . to run.

  4. Support for multithreading: The Java language has built-in multithreading control, which allows user programs to execute concurrently. Using Java's multi-threaded programming interface, developers can easily write multi-threaded application programs to improve program execution efficiency.

  5. Others: safe and reliable, coexistence of compilation and interpretation, support for network programming, etc.

3. What is the difference between JVM, JDK and JRE?

  1. JVM : Java virtual machine, Java programs run on the Java virtual machine. Different JVMs are implemented for different systems, so the Java language can be cross-platform.

  2. JRE : Java Runtime Environment, which is a collection of everything needed to run a compiled Java program, including JVM, Java class library, Java command and some other things.

  3. JDK : Java Development Kit, including JRE.

Three relationship

4. What is bytecode? What are the benefits of bytecode?

  • The code that the JVM can understand is the bytecode (.class)

  • The .class and bytecode generated by the compiled Java program can be recognized by the virtual machine, and different JVMs are installed on different platforms, so as to realize the cross-platform nature of the Java program.

The three steps of running a Java program:

  1. **Compile:** Compile .java into .class
  2. **Explanation: **JVM interprets .class as machine code
  3. **Execution: **Machine code execution

5. Why is it said that the Java language "compilation and interpretation coexist"?

First understand the concept, high-level programming languages ​​are divided into two types according to the way the program is executed:

  • Compiled type : Compiled language uses a compiler to translate the source code into machine code that can be executed by the platform at one time. For example, C, C++, GO, Rust, etc.
    • Advantages : faster execution speed (so those algorithm competitions are mainly C++).
    • Disadvantages : low development efficiency.
  • Interpreted : An interpreted language will interpret the code sentence by sentence through the interpreter into machine code. For example, Python, JavaScript, PHP, etc.
    • Advantages : fast development efficiency.
    • **Disadvantages:** Slow execution.

If you have read all the previous points, you should be able to roughly understand what it means to coexist with Java language compilation and interpretation! The execution of a Java program must first be compiled and then interpreted. Between these two concepts, it has the characteristics of two high-level languages.

6. Java basic data types?

Eight basic data types:

basic type number of digits byte **Defaults** Ranges
byte 8 1 0 -128~127
short 16 2 0 -32768~32767
int 32 4 0 -2147483648 ~ 2147483647
long 64 8 0L -9223372036854775808 ~ 9223372036854775807
char 16 2 ‘u0000’ 0 ~ 65535
float 32 4 0 f 1.4E-45 ~ 3.4028235E38
double 64 8 0d 4.9E-324 ~ 1.7976931348623157E308
boolean 1 false true、false

For boolean, different JVM vendors have different implementations.

Reference data types:
classes, interfaces, arrays

7. Automatic type conversion, forced type conversion?

Automatic Type Conversion Direction
Automatic type conversion : It is low-precision to high-precision conversion (at most, the precision of .0000 will be added later, and the precision will not be lost).

Mandatory type conversion : It is high-precision to low-precision conversion (for example, if 1.999 becomes low-precision, it becomes 1, which is almost 2, can you tell me if this is possible).

8. Do you understand automatic boxing and unboxing? What is the principle?

Automatic boxing and unboxing:

  • Boxing : Wrap primitive types with their corresponding reference types .
  • Unboxing : converting a wrapped type to a primitive data type .

Principle :
Boxing is actually calling the valueOf() method of the packaging class, and unboxing is actually calling the xxxValue() method.

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

  1. A class can implement multiple interfaces, but only one abstract class. The interface itself can extend multiple interfaces through the extends keyword.

  2. The default modifier for interface methods is public, and abstract methods can have modifiers such as public, protected, and default.

  3. All methods in the interface cannot be implemented (interface methods can have default implementations starting from jdk8), and abstract classes can have non-abstract methods.

  4. From a design perspective, abstraction is an abstraction of classes, which is a template design, while an interface is an abstraction of behaviors, which is a specification of behaviors.

  5. In addition to static and final variables, there cannot be other variables in the interface, but not necessarily in abstract classes.

10. What is the difference between String, StringBuilder and StringBuffer?

  • String : The value of String cannot be modified after it is created, and any modification to String will trigger the generation of a new String object.

  • StringBuffer : Similar to String, but the value can be modified without causing a new StringBuffer object to be generated, using synchronized to ensure thread safety, suitable for multi-threading.

  • StringBuilder : Similar to StringBuffer, but not thread-safe, suitable for single-thread, with higher performance.

11. What data types can Switch cases support?

Previously, Java5 could only support byte, short, char, and int. The enum type is supported after Java5. Since Java7, String is supported, but long is not applicable in all versions.

12. What is the difference between character constants and string constants?

** ** **Form** meaning memory size
character constant characters enclosed in single quotes A character is equivalent to an integer value and can participate in expression operations 2 bytes
string constant 0 or more characters enclosed by double quotes string representing an address several bytes

13. Look at the values ​​of the following self-increment operations?

int i  = 1;
i = i++;
System.out.println(i);

答案为1

int count = 0;
for(int i = 0;i < 100;i++)
{
    
    
    count = count++;
}
System.out.println("count = "+count);

答案为0

Is it not the same as what you think, here is when the self-increment operation is performed, another temporary variable will be stored to accept the value of i or count, and then the temporary variable will be assigned to i or count, and finally is The above results.

14. What is the difference between static methods (variables) and instance methods (variables)?

** ** ** static method ** instance method
calling method The usual **类名.方法名**way (calling static methods without creating objects, often seen in tool classes) You must first create an object and then use **对象.方法名**it to call
Whether access to class members is restricted When a static method accesses members of this class, it is only allowed to access static members (static variables and static methods) casual access
** static variable ** ** instance variable**
Modified by static, it belongs to the class, but does not belong to any object of the class. No matter how many objects are created in a class, there is only one copy of the static variable in memory. You need to create an object first and then access it through the object, each object is an independent copy

15. What is the difference between overload and override?

  • Both method overloading and rewriting are ways to achieve polymorphism. The difference is that the former implements compile-time polymorphism, while the latter implements run-time polymorphism.
method overloading ** Occurred in the same class, the method name is the same, the parameter type order, type, and number are different, different exceptions can be thrown, and different modifiers can be used**
method override Occurs in subclasses and parent classes, requires the overridden method of the parent class to have the same return type, and cannot declare more exceptions than the overridden method of the parent class

16. What is the difference between object-oriented and process-oriented?

  • Object Oriented (OO): first abstract the object, and then use the object to execute the method to solve the problem.

  • Process Oriented (Procedure Oriented: OP): Break down the problem-solving process into methods, and solve problems through the execution of each method

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

image.png

18. What is the function of this keyword?

  1. Ordinary direct references point to something in the object itself, as opposed to the object itself.

  2. When the name of the formal parameter and the actual parameter are repeated, use this to distinguish

  3. access constructor

19. What is the role of the final keyword?

final means immutable and can be used to modify classes, properties and methods.

  1. Classes modified by final cannot be inherited

  2. Methods modified by final cannot be overridden (just like sterilization)

  3. The variable modified by final is immutable, and the value must also be initialized. The immutable here refers to the immutable reference of the variable, not the immutable content of the reference.

20. What is the difference between the three keywords final, finally, and finalize?

  • final see above

  • finally is often try/catchused together, and its statement block will be executed anyway.

What is mentioned above is the general situation, but if you encounter the following three situations, it may not be executed:

  1. The virtual machine is terminated before finally
  2. The thread where the program is located dies
  3. turn off the cpu
  • finalize is java.lang.Objecta method defined in , that is to say, each object has such a method, which is gccalled when the object is started and recycled.

The finalize method of an object will only be called once, and the finalize call may not immediately reclaim the object, so it is possible that after calling finalize, the object does not need to be reclaimed, and then when it is really about to be reclaimed, because the previous call Once, so finalize will not be called again, which will cause problems, so the finalize method is not recommended

21. Is Java passed by value or by reference?

Java is passed by value. First understand the basic types and reference types.
image.png

public class test {
    
    
    public static void main(String[] args) {
    
    
        int num = 10;
        System.out.println(num); // 10
        jia(num);
        System.out.println(num); // 10
    }
    public static void jia(int num1) {
    
    
        num1++;
    }
}

public class test {
    
    
    public static void main(String[] args) {
    
    
        String str = "hello";
        System.out.println(str); // hello
        jia(str);
        System.out.println(str); // hello
    }
    public static void jia(String str1) {
    
    
        str1 = "world";
    }
}

The first set of codes, when we call the method jia, pass the past num, after num1++, the num output in main has not changed.
The second set of code is similar to the one above. When we str1="world", that is, the place pointed to by str1 has changed, and the "hello" pointed to by str will not be affected.
Here it can be proved that num and num1 are not the same thing, and str and str1 are not the same reference, so we call this thing called value transfer.

image.png

public class test {
    
    
    /**
     * public class A {
     *    String str = "hello";
     * }
     */
    public static void main(String[] args) {
    
    
        A a = new A();
        System.out.println(a.str); // hello
        jia(a);
        System.out.println(a.str); // world
    }
    public static void jia(A str1) {
    
    
       str1.str = "world";
    }
}

Didn’t it mean passing by value? Why has str changed again? The str modified by the jia method here is actually the same as the place pointed to by str in a, but overall it is still passing by value. The a object and the a1 object are two a different reference.

22. What is the difference between == and equals?

Use of ==:

  • For primitive types, **==**values ​​are compared.
  • For reference types, **==**the memory address of the object is compared.

Use of equals:

  • The class does not override this method, which is equivalent to**==**
  • The class overrides this method to compare whether the contents of the two objects are equal

When we use String, we use equals for comparison. This is because String rewrites the equals and hashCode methods to compare whether the content is the same.

23. Why must the hashCode() method be rewritten when rewriting equals()?

The equals method judges that two objects are equal, then the hashcode values ​​​​of the two objects must also be equal. If you rewrite equals without rewriting hashCode, it may cause equals to judge that it is the two objects you want, but their hashCode values ​​are not equal.

That is to say:

  • equalsmethod to determine that two objects are equal, then hashcodethe values ​​​​of the two objects must also be equal.
  • Two objects have the same hashcodevalue, they are not necessarily equal (hash collision).

24. Is String a basic data type in Java? Can it be inherited?

String is not a basic data type of Java, and there are only 8 basic data types.

The String class is finalized, and the character array storing the string in the String class is also finalized and cannot be inherited.

25. Do you use "+" or StringBuilder for string splicing?

Judging from the bytecode, it is actually implemented through the append method of StringBuilder. After +, use toString to get a String object .+

Before Jdk9, if + is used in the loop, a StringBuilder object will be created every time the loop is used. Direct use of StringBuilder will not do this. After Jdk9, the problem of repeatedly creating StringBuilder objects has been fixed.

26. String s1 = new String("abc"); How many string objects are created by this sentence?

  • If there is no reference to the string object "abc" in the string constant pool, then 2 string objects "abc" will be created in the heap:
String s1 = new String("abc");

A String object will be created in the heap, then an "abc" string object will be created in the constant pool, and then the String object in the heap will be initialized.

  • If there is already a reference to the string object "abc" in the string constant pool, only one string object "abc" will be created in the heap:
// 字符串常量池中已存在字符串对象“abc”的引用
String s1 = "abc";
// 下面这段代码只会在堆中创建 1 个字符串对象“abc”
String s2 = new String("abc");

Create a String object in the heap and initialize it directly from "abc" in the constant pool.

27. What is the function of the intern method?

String.intern()It is a native method that saves the reference of the specified string object in the string constant pool:

  • If the current string content exists in the string constant pool, directly return the reference in the string constant pool.
  • Otherwise, the String object is added to the pool and a reference to the String object is returned.

You can refer to the intern method_wzdhc's blog-CSDN blog

28. Java exception system? What is the difference between checked and unchecked exceptions?

  • Checked Exception is a checked exception: During the compilation process, the compiler will forcibly check and require handling of exceptions.
  • Unchecked Exception is an unchecked exception. RuntimeException and its subclasses are collectively referred to as unchecked exceptions: during compilation, the compilation can pass normally even if the checked exception is not handled.
** **NullPointerException ** ** Null pointer error
IllegalArgumentException Parameter error such as method input parameter type error
NumberFormatException string to number format error
ArrayIndexOutOfBoundsException Array out of bounds error
ClassCastException type conversion error
ArithmeticException arithmetic error
SecurityException Security errors such as insufficient permissions
UnsupportedOperationException Unsupported operation errors such as repeated creation of the same user

common exception

29. Serialization and deserialization? How to serialize? What if you don't want to serialize?

  • 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 during serialization into a data structure or object

Applicable scenarios: Persisting Java objects (Redis storage), transferring Java objects in the network (RPC remote call),通俗来说,就是将一个东西拆开,然后运输,最后再组装起来

There are currently three serialization methods:

  1. Java对象序列化: The Java native serialization method is converted through the Java native stream InputStream and OutputStream
  2. JSON序列化: This is the serialization method I have seen the most. Common packages include Jackson, FastJson
  3. ProtoBuff 序列化: ProtocolBuffer is a lightweight and efficient structured data storage format. ProtoBuff serialized objects can compress it to a large extent, which can greatly reduce the size of data transmission and improve system performance

If some variables in the object do not want to be serialized, use transientkeyword modification.

  1. Prevent serialization of variables modified by this keyword in the instance, and when the object is deserialized, the variables modified by it will not be restored.
  2. This keyword can only modify variables, not classes and methods.

30. What is generic? What are the ways to use it? Commonly used wildcards?

  • Java generics is a feature introduced in JDK5. Using generic parameters can enhance the readability and stability of the code.

  • The compiler can detect the generic parameters, and can specify the type of object passed in through the generic parameter, such as List lists = new ArrayList() This line of code indicates that the ArrayList object can only be passed in the Person object, if passed in Objects of other types will report an error.

The general usage methods are: generic class, generic interface, generic method

  1. generic class
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型
public class Generic<T>{
    
    

    private T key;

    public Generic(T key) {
    
    
        this.key = key;
    }

    public T getKey(){
    
    
        return key;
    }
}

Generic<Integer> genericInteger = new Generic<Integer>(123456);
  1. generic interface
public interface Generator<T> {
    
    
    public T method();
}

class GeneratorImpl<T> implements Generator<String>{
    
    
    @Override
    public String method() {
    
    
        return "hello";
    }
}
  1. generic method
public static < E > void printArray( E[] inputArray )
{
    
    
     for ( E element : inputArray ){
    
    
        System.out.printf( "%s ", element );
     }
     System.out.println();
}

Commonly used wildcards are: T, E, K, V, ?

  • ? Represents an indeterminate java type
  • T (type) represents a specific java type
  • KV (key value) respectively represent the Key Value in the java key value
  • E (element) stands for Element

31. What are the IO streams in Java?

  • According to the flow direction of the flow, it can be divided into 输入流and输出流
  • According to the operation unit, it can be divided into 字节流and字符流
  • According to the role of the flow, it is divided into 节点流and处理流

IO flow uses a design pattern - decorator pattern

32. Tell me about your understanding of annotations? What are the methods for analyzing annotations?

  • 注解It is a new feature introduced after Java5. It can be regarded as a special annotation. It is mainly used to modify classes, methods, variables, etc., and provide some information for the program to use when compiling or running. The essence of the annotation is an inheritance of Annotation special interface for

  • There are two common annotation analysis methods:

    • Direct scanning during compilation: The compiler scans and processes the corresponding annotations when compiling the java code.
    • The runtime is processed by reflection: the annotations that come with the framework (Spring, mybaits) are all processed by reflection

33. What is reflection? Advantages and disadvantages? Application scenario? principle?

  • What is reflection: We want to use reflection when dynamically obtaining class information, creating class instances, and calling class methods. All properties and methods of any class can be obtained through reflection, and these methods and properties can also be called.

  • Advantages and disadvantages of reflection:

    • Advantages: Reflection can make our code more flexible and provide out-of-the-box functionality for various frameworks
    • Disadvantages: It increases security issues and can ignore the security checks of generic parameters; the performance of reflection is also almost
  • Application scenarios: Many designs and developments are related to the reflection mechanism, such as modular development, which calls the corresponding bytecode through reflection, and the dynamic proxy design mode also uses the reflection mechanism, for example as follows:

    • JDBC database connection
    • Use of Spring framework
  • Principle: The execution of a Java program is divided into two steps: compilation and operation. After compilation, a bytecode file will be generated. When the JVM loads a class, it will load the bytecode file and load all the information related to the type into the method area. Reflection is to obtain this information, and then perform various operations

34. Have you ever used Stream?

Stream, in simple terms, uses java.util.Stream to perform various operations on a collection containing one or more elements. These operations may be intermediate operations or terminal operations . Terminal operations return a result, while intermediate operations return a Stream.

  • Filter
  • Sorted
  • Conversion (Map)
  • Match
  • Count
  • Etc., etc

image.png

35. New features of jdk1.8?

  1. Default interface method: Allows to add non-abstract methods to the interface, through the keyword default
  2. Lambda expression and functional interface: Lambda expression is essentially an anonymous inner class, and it can also be a piece of code that can be passed. Lambda allows functions to be used as parameters of a method, using Lambda expressions to make the code more concise.
  3. Stream API: A tool for performing complex operations on collection classes in a functional programming manner. With Lambda expressions, it is convenient to process collections.
  4. Time Date API: Java 8 introduces new date time classes.
  5. Optional Resolves NullPointerException

Guess you like

Origin blog.csdn.net/weixin_52487106/article/details/130833310