Six years of interview experience to share basic JAVA interview questions

Source | Jilian AI Cloud (the most cost-effective shared GPU computing platform, newcomers register directly to send a gift package of 198 yuan! Free trial address : https://cloud.videojj.com/ )

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

Process-oriented

Advantages: performance is higher than object-oriented, because the class needs to be instantiated when calling, the overhead is relatively large, and it consumes more resources. For example, single-chip microcomputer, embedded development, Linux/Unix, etc. generally adopt process-oriented development, and performance is the most important factor.

Disadvantages: no object-oriented, easy to maintain, easy to reuse, easy to expand

Object-oriented

Advantages: easy to maintain, easy to reuse, easy to expand, because object-oriented has the characteristics of encapsulation, inheritance, and polymorphism, a low-coupling system can be designed, making the system more flexible and easier to maintain

Disadvantages: performance is lower than process-oriented

2. What are the characteristics of the Java language

1. Easy to learn;

2. Object-oriented (encapsulation, inheritance, polymorphism);

3. Platform independence (Java virtual machine realizes platform independence);

4. Reliability;

5. Security;

6. Support multithreading (C++ language does not have a built-in multithreading mechanism, so the multithreading function of the operating system must be called for multithreading programming, while Java language provides multithreading support);

 

7. Supports network programming and is very convenient (the birth of Java language itself is designed to simplify network programming, so Java language not only supports network programming but also very convenient);

8. Coexistence of compilation and interpretation;

3. The most detailed and popular answers about JVMJDK and JRE

JVM

The Java Virtual Machine (JVM) is a virtual machine that runs Java bytecode. JVM has specific implementations for different systems (Windows, Linux, macOS), the purpose is to use the same bytecode, they will all give the same result.

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

In Java, the code that the JVM can understand is called bytecode (that is, a file with a .class extension), which is not oriented to any specific processor, but only oriented to the virtual machine. Java

The language uses bytecode to solve the problem of low execution efficiency of traditional interpreted languages ​​to a certain extent, while retaining the portability of interpreted languages. Therefore, the Java program is more efficient when it runs, and because the bytecode is not specific to a specific machine, the Java program can run on a variety of different computers without recompiling.

Java programs generally have the following 3 steps from source code to operation:

We need to pay special attention to the step of .class->machine code. In this step, the jvm class loader first loads the bytecode file, and then interprets and executes it line by line through the interpreter. The execution speed of this method will be relatively slow. Moreover, some methods and code blocks need to be called frequently, which is the so-called hot code, so they are introduced later

JIT compiler, JIT belongs to runtime compilation. When the JIT compiler completes the first compilation, it saves the machine code corresponding to the bytecode, and can be used directly next time. And we know that the efficiency of machine code is definitely higher than that of the Java interpreter. This also explains why we often say that Java is a language where compilation and interpretation coexist.

HotSpot uses LazyEvaluation, which consumes most of the

System resources are only a small part of the code (hot code), and this is what JIT needs to compile

part. The JVM collects information based on each execution of the code and makes some optimizations accordingly. Therefore, the more times it is executed, the faster it will be. JDK9

A new compilation mode AOT (Ahead of Time Compilation) is introduced, which directly compiles bytecode into machine code, thus avoiding

JIT preheating and other aspects of overhead. JDK supports layered compilation and AOT collaborative use. However, the compilation quality of AOT compiler is definitely not as good as JIT

Compiler.

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

 

JDK和JRE

JDK is JavaDevelopmentKit, which is a fully functional JavaSDK. It has everything the JRE has, as well as the compiler (javac) and tools (such as javadoc and jdb). It can create and compile programs. JRE is the Java runtime environment. It is a collection of everything needed to run a compiled Java program, including the Java Virtual Machine (JVM), Java class libraries, java commands and other basic components. However, it cannot be used to create new programs. If you just want to run Java

Program, then you only need to install JRE. If you need to do some Java programming work, then you need to install JDK

Up. However, this is not absolute. Sometimes, even if you don’t plan to do any Java development on your computer, you still

Need to install JDK. For example, if you want to deploy a web application using JSP, then technically speaking, you are just running a Java program in the application server. So why do you need JDK? Because the application server will convert JSP to Java servlet, and need to use JDK to compile the servlet.

4. Comparison of OracleJDK and OpenJDK

Maybe many people like me have not touched or used OpenJDK before looking at this issue. So is there a major difference between Oracle and OpenJDK? Below, through some information I have collected, I will answer this question that is ignored by many people. For Java 7, there is nothing critical. The OpenJDK project is mainly based on the HotSpot source code donated by Sun. In addition, OpenJDK was selected as the reference implementation of Java7, maintained by Oracle engineers. Regarding the difference between JVM, JDK, JRE and OpenJDK, an Oracle blog post in 2012 has a more detailed answer:

Q: What is the difference between the source code in the OpenJDK repository and the code used to build OracleJDK?

Answer: Very close-our OracleJDK version build process is based on OpenJDK7, only a few parts are added, such as deployment code, which includes the implementation of Oracle's Java plug-in and JavaWebStart, and some closed source code party components, such as graphics rasterization Some open source third-party components, such as

Rhino, and some odds and ends, such as additional documents or third-party fonts. Looking to the future, our goal is to open source all parts of OracleJDK, except for the part where we consider commercial functions.

to sum up:

1. The OracleJDK version will be released every three years, and the OpenJDK version will be released every three months;

2. OpenJDK is a reference model and is completely open source, while OracleJDK is an implementation of OpenJDK, not completely open source;

3. OracleJDK is more stable than OpenJDK. The code of OpenJDK and OracleJDK are almost the same, but OracleJDK has more classes and some bug fixes. Therefore, if you want to develop enterprise/commercial software, I suggest you choose OracleJDK because it has been thoroughly tested and stable. In some cases, some people mentioned that they may encounter many application crashes when using OpenJDK, but just switch to OracleJDK to solve the problem;

4. Top companies are using OracleJDK, such as AndroidStudio, Minecraft and IntelliJIDEA development tools, of which OpenJDK is not very popular;

5. In terms of responsiveness and JVM performance, OracleJDK provides better performance than OpenJDK;

6. OracleJDK will not provide long-term support for the upcoming version, and users must obtain the latest version by updating to the latest version to obtain support each time;

7. OracleJDK is licensed under the Binary Code License Agreement, and OpenJDK is licensed under the GPLv2 license.

5. The difference between Java and C++

I know that many people have never studied C++, but the interviewer just likes to compare Java and C++! no way! ! ! Even if you have never learned C++, write it down!

 Both are object-oriented languages ​​and support encapsulation, inheritance and polymorphism

 Java does not provide pointers to directly access memory, and program memory is more secure

 Java classes are single inheritance, and C++ supports multiple inheritance; although Java classes cannot be multiple inheritance, interfaces can be multiple inheritance.

 Java has an automatic memory management mechanism that does not require programmers to manually release useless memory

6. What is the main class of a Java program? What is the difference between the main class of an application and a small program?

There can be multiple classes in a program, but only one class can be the main class. In a Java application, this main class refers to the class that contains the main() method. In Java applets, this main class is a subclass inherited from the system class JApplet or Applet. The main class of an application is not necessarily required to be a public class, but the main class of an applet must be a public class. The main class is the entry point for Java program execution.

7. What are the differences between Java applications and applets

Simply put, the application is started from the main thread (that is, the main() method). The applet applet does not have a main method. It is mainly embedded in the browser page to run (call init() thread or run() to start). The embedded browser is similar to flash games.

8. The difference between character constants and string constants

1. Formally: A character constant is a character surrounded by single quotation marks. A string constant is a number of characters surrounded by double quotation marks.

2. Meaning: A character constant is equivalent to an integer value (ASCII value), which can participate in expression operations. A string constant represents an address value (the string is stored in the memory)

3. Occupy memory size. Character constants only occupy 2 bytes. String constants occupies several bytes (at least one character end flag) (Note: char occupies two bytes in Java) 

9. Can Constructor be overridden

When talking about inheritance, we know that the private properties and construction methods of the parent class cannot be inherited, so the Constructor cannot be overridden, but it can be overloaded, so you can see that there are The case of multiple constructors.

10. The difference between overloading and rewriting

Overloading: Occurs in the same class, the method name must be the same, the parameter type is different, the number is different, the order is different, the method return value and access modifier can be different, and it occurs at compile time.

Rewrite: Occurs in the parent and child class, the method name, parameter list must be the same, the return value range is less than or equal to the parent class, the thrown exception range is less than or equal to the parent class, access modifier

The scope is greater than or equal to the parent class; if the parent class method access modifier is private, the child class cannot override the method.

11. Three characteristics of Java object-oriented programming: encapsulation inheritance polymorphism

Package

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

inherit

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

Please remember the following 3 points about inheritance:

1. The child class has non-private properties and methods of the parent class.

2. The subclass can have its own properties and methods, that is, the subclass can extend the parent class.

3. The subclass can implement the method of the parent class in its own way.

Polymorphism

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

12. What is the difference between String StringBuffer and StringBuilder Why String is immutable

Variability

To put it simply: the String class uses the final keyword character array to save the string, privatefinal char value[], so the String object is immutable. StringBuilder and StringBuffer both inherit from the AbstractStringBuilder class. In AbstractStringBuilder, a character array is also used to store the string char[]value but it is not decorated with the final keyword, so both objects are mutable.

The construction methods of StringBuilder and StringBuffer both call the parent class construction method, which is

As implemented by AbstractStringBuilder, you can check the source code yourself.

AbstractStringBuilder.java

abstract class AbstractStringBuilder implements Appendable, CharSequence {

char[] value;

int count;

AbstractStringBuilder() { 

}

AbstractStringBuilder(int capacity) {

value = new char[capacity];

}

Thread safety

Objects in String are immutable, which can be understood as constants and thread-safe. AbstractStringBuilder is the public parent class of StringBuilder and StringBuffer, and defines some basic string operations, such as expandCapacity, append, insert, indexOf and other public methods. StringBuffer adds a synchronization lock to the method or adds a synchronization lock to the called method, so it is thread-safe. StringBuilder does not add synchronization lock to the method, so it is not thread-safe.

performance

Every time the String type is changed, a new String object is generated, and then the pointer is pointed to the new String object. StringBuffer operates on the StringBuffer object itself every time, instead of generating new objects and changing object references. In the same situation, using StringBuilder can only get a performance improvement of about 10%~15% compared to using StringBuffer, but it will take the risk of multithreading insecurity.

A summary of the use of the three:

1. Operate a small amount of data = String

2. Operate large amounts of data in a single-threaded string buffer = StringBuilder

3. Operate large amounts of data under multi-threaded operation string buffer = StringBuffer

13. Automatic packing and unpacking

Packing : Pack basic types with their corresponding reference types;

Unboxing : Convert the packaging type to the basic data type;

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

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

15. Define the role of a constructor that does nothing and has no parameters in Java

Before the Java program executes the construction method of the subclass, if the super() is not used to call the specific construction method of the parent class, it will call the "construction method without parameters" in the parent class. Therefore, if only a parameterized construction method is defined in the parent class, and the super() is not used in the construction method of the subclass to call the specific construction method in the parent class, an error will occur at compile time, because the Java program A constructor with no parameters can not be found in the parent class for execution. The solution is to add a construction method that does nothing and has no parameters in the parent class.

16. What is the difference between import java and javax

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

17. What is the difference between an interface and an abstract class

1. The interface method is public by default, all methods cannot be implemented in the interface (interface methods can have default implementations since Java 8), and abstract classes can have non-abstract methods

2. The instance variable in the interface is final by default, but not necessarily in the abstract class

3. A class can implement multiple interfaces, but only one abstract class can be implemented at most

4. If a class implements an interface, it must implement all the methods of the interface, but an abstract class may not

5. The interface cannot be instantiated with new, but it can be declared, but it must reference an object that implements the interface. From a design perspective, abstraction is an abstraction of a class, a template design, and an interface is an abstraction of behavior. Norms of behavior.

18. What are the differences between member variables and local variables

1. From the grammatical form, the member variable belongs to the class, and the local variable is the variable defined in the method or the method parameter; the member variable can be modified by public, private, static and other modifiers, but the local variable cannot Modified by access control modifiers and static; however, member variables and local variables can be modified by final;

2. From the perspective of how variables are stored in memory, member variables are part of the object, and the object exists in the heap memory, and local variables exist in the stack memory

3. From the point of view of the survival time of variables in memory, member variables are part of the object. They exist with the creation of the object, while local variables disappear automatically with the call of the method.

4. If a member variable is not assigned an initial value, it will be automatically assigned with the default value of the type (except in one case, member variables modified by final must also be explicitly assigned); local variables will not be assigned automatically.

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

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

20. What is the return value of the method? What is the role of the return value in the method of the class?

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

21. What is the role of a class's constructor? If a class does not declare a constructor, can the program be executed correctly? Why?

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

22. What are the characteristics of the construction method

1. The name is the same as the class name;

2. There is no return value, but the constructor cannot be declared with void;

3. It is automatically executed when the object of the class is generated, without calling.

23. What is the difference between static methods and instance methods

1. When calling a static method externally, you can use the "class name. method name" method or the "object name. method name" method. The instance method has only the latter way. In other words, you can call static methods without creating objects.

2. When a static method accesses the members of this class, only static members (ie, static member variables and static methods) are allowed to access, but not instance member variables and instance methods; there is no such restriction for instance methods.

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

The equality of objects is compared to whether the contents stored in the memory are equal. While the references are equal, the comparison is whether the memory addresses they point to are equal.

25. Before calling the subclass's construction method, the parent class's construction method without parameters will be called first. What is the purpose?

Help subclasses to do initialization work.

26. == and equals (important)

==: Its function is to judge whether the addresses of two objects are equal. That is, it is judged whether two objects are the same object. (The basic data type == compares the value, and the reference data type == compares the memory address) equals(): Its function is to judge whether two objects are equal. But it generally has two use cases:

 Case 1: The class does not cover the equals() method. When comparing two objects of this class through equals(), it is equivalent to comparing the two objects through "==".

 Case 2: The class covers the equals() method. Generally, we cover the equals() method to make the contents of two objects equal; if their contents are equal, it returns true (that is, the two objects are considered equal).

for example:

public class test1 {

public static void main(String[] args) {

String a = new String("ab"); // a is a reference

String b = new String("ab"); // b is another reference, the content of the object is the same

String aa = "ab"; // put in the constant pool

String bb = "ab"; // Find from the constant pool

if (aa == bb) // true

System.out.println("aa==bb");

if (a == b) // false, not the same object

System.out.println("a==b");

if (a.equals(b)) // true

System.out.println("aEQb");

if (42 == 42.0) { // true

System.out.println("true");

}

Description:

 The equals method in String has been 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 object with the same value as the value to be created, and assigns it to the current reference if there is one. If not, recreate a String object in the constant pool.

27. hashCode and equals (important)

The interviewer may ask you: "Have you rewritten hashcode and equals? Why do you have to rewrite the hashCode method when rewriting equals?"

Introduction to hashCode()

The purpose of hashCode() is to obtain a hash code, also called a hash code; it actually returns an int integer. The function of this hash code is to determine the index position of the object in the hash table. hashCode() is defined in Object.java of the JDK, which means that any class in Java contains the hashCode() function.

The hash table stores key-value pairs, and its characteristic is that it can quickly retrieve the corresponding "value" based on the "key". Among them, the hash code is used! (You can quickly find the object you need)

Why is there a hashCode

Let's take "How does HashSet check for duplicates" as an example to illustrate why there is a hashCode:

When you add an object to a HashSet, HashSet will first calculate the object's hashcode value to determine where the object is added, and compare it with the hashcode values ​​of other added objects. If there is no matching hashcode, HashSet will assume that the object is not duplicate appear. But if an object with the same hashcode value is found, the equals() method will be called to check whether the objects with equal hashcode are really the same. If the two are the same, HashSet will not let it join the operation successfully. If they are different, they will be hashed to another location. (Excerpt from the second edition of my Java Enlightenment book "Headfirst java"). In this way, we greatly reduce the number of equals, and accordingly greatly improve the execution speed.

HashCode () and equals () related regulations

1. If the two objects are equal, the hashcode must also be the same

2. The two objects are equal, and the equals method on the two objects respectively returns true

3. Two objects have the same hashcode value, and they are not necessarily equal

4. Therefore, the equals method is overridden, the hashCode method must also be overridden

5. The default behavior of hashCode() is to generate unique values ​​for objects on the heap. If hashCode() is not overridden, the two objects of the class will not be equal anyway (even if the two objects point to the same data)

 

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

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

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

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

29. What are the basic states of threads?

Refer to section 4.1.4 of "Java Concurrent Programming Art".

A Java thread can only be in one of the following six different states at a specified time in the life cycle of its operation.

Threads are not fixed in a certain state during the life cycle but switch between different states as the code executes.

30 Some conclusions about the final keyword

The final keyword is mainly used in three places: variables, methods, and classes.

1. For a final variable, 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 made to point to another object after its initialization.

2. When a class is modified with final, it indicates that the class cannot be inherited. All member methods in the final class will be implicitly designated as final methods.

3. There are two reasons for using final methods. The first reason is to lock the method in case any inherited classes modify its meaning; the second reason is efficiency. In earlier versions of Java implementation, final methods will be converted to inline calls. But if the method is too large, you may not see any performance improvement brought by the inline call (the current Java version no longer needs to use final methods for these optimizations). All private methods in the class are implicitly designated as final.

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

For variables that do not want to be serialized, use transient keyword modification.

The purpose of the transient keyword is to prevent the serialization of variables modified by this keyword in the instance;

When the object is deserialized, the variable value modified by transient will not be persisted and restored.

transient can only modify variables, not classes and methods.

32 Get the two commonly used methods of keyboard input

Method 1: Via Scanner

Scanner input = new Scanner(System.in);

String s = input.nextLine();

input.close();

方法 2:通过 BufferedReaderBufferedReader input = new BufferedReader(new InputStreamReader(System.in));

String s = input.readLine();

 

Source | Jilian AI Cloud (the most cost-effective shared GPU computing platform, newcomers register directly to send a gift package of 198 yuan! Free trial address : https://cloud.videojj.com/ )

Want more learning materials add me vx: weiweigogogo888

Send you the information for free

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_51072772/article/details/109027257