Reference: https://mp.weixin.qq.com/s/eFUEw21qNIwHlyUJd7pSkw




directory

1. The difference between object-oriented and procedural

2. What are the features of the Java language

JVM JDK and JRE

4. Oracle JDK vs. OpenJDK

5. The difference between Java and C++

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

7. What are the differences between Java applications and applets

8. Difference between character constants and string constants

9. Whether Constructor Constructor can be overridden

10. Difference between overloading and overwriting

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

What is the difference between a StringBuffer and a StringBuilder

13. Automatic packing and unpacking

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

15. The role of defining a do-nothing, no-arguments constructor in Java

What is the difference between import Java and Javax

What is the difference between an interface and an abstract class

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

19. What operator is used to create an object? How is an object entity different from an object reference?

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

21. What does a class constructor do if a class does not declare a constructor, does the program execute correctly? Why is that?

22. What are the properties of the constructor

23. What is the difference between static and instance methods

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

The subclass constructor with no arguments is called before the subclass constructor is called.

26. == equals(important)

27. HashCode and Equals (Important)

28. Why is there only value passing in Java

29. Describe the basic concepts of threads, programs, and processes. And what is the relationship between them

30. What are the basic states of threads?

31 Summary of the final keyword

32 Exception handling in Java

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

34 Get two common methods of keyboard input

reference

1. The difference between object-oriented and procedural

Process oriented

Advantages: Higher performance than object-oriented, because class invocation needs to be instantiated, the overhead is relatively large, more consumption of resources; For example, SCM, embedded development, Linux/Unix and so on generally adopt process-oriented development, performance is the most important factor.

Disadvantages: No object-oriented easy maintenance, easy reuse, easy to expand

object-oriented

Advantages: easy to maintain, easy to reuse, easy to expand, because of the characteristics of object-oriented encapsulation, inheritance, polymorphism, can design a low coupling system, make the system more flexible, more easy to maintain

Disadvantages: Lower performance than process-oriented

2. What are the features of the Java language

  1. Simple and easy to learn;

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

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

  4. Reliability;

  5. Security;

  6. Support multithreading (C++ language does not have built-in multithreading mechanism, so must call the multi-threading function of the operating system to multithreading programming, and the Java language has provided multithreading support);

  7. Network programming is supported and convenient (the Java language itself was designed to simplify network programming, so the Java language not only supports network programming but also is convenient);

  8. Compilation and interpretation coexist;

JVM JDK and JRE

JVM

A Java Virtual machine (JVM) is a virtual machine that runs Java bytecode. The JVM has specific implementations for different systems (Windows, Linux, macOS) that aim to use the same bytecode, and they all give the same results.

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

In Java, code that can be understood by the JVM is called bytecodes (files with a.class extension) that are not oriented to any particular processor, just to the virtual machine. Java solves the problem of low efficiency of traditional interpreted languages by means of bytecode to some extent, and at the same time retains the portability of interpreted languages. So Java programs run more efficiently, and because bytecode is not specific to a particular machine, Java programs can run on many different machines without recompiling.

Java programs from source to run generally have the following three steps:

We need to pay special attention to the.class-> machine code step. In this step, the JVM classloader loads the bytecode file and then executes it line by line through the interpreter, which is relatively slow. In addition, some methods and code blocks need to be called frequently, which is called hot code, so the JIT compiler was introduced later. JIT is runtime compilation. When the JIT compiler completes the first compilation, it saves the machine code corresponding to the bytecode for direct use next time. And we know that machine code is certainly more efficient than Java interpreters. This explains why we often talk about Java as a compilation and interpretation language.

HotSpot adopts Lazy Evaluation, where, according to the 80/20 rule, only a small portion of code (hot code) consumes most of the system’s resources, and that is what the JIT needs to compile. The JVM collects information based on each time the code is executed and makes some optimizations accordingly, so the more times it executes, the faster it gets. JDK 9 introduces a new Compilation mode, AOT(Ahead of Time Compilation), which compiles bytecode directly to machine code, thus avoiding overhead such as JIT warm-up. The JDK supports hierarchical compilation and AOT collaboration. However, AOT compilers are certainly not as good as JIT compilers.

Summary: A Java Virtual machine (JVM) is a virtual machine that runs Java bytecode. The JVM has specific implementations for different systems (Windows, Linux, macOS) that aim to use the same bytecode, and they all give the same results. Bytecode and JVM implementations for different systems are key to the Java language’s “compile once, run anywhere” approach.

The JDK and JRE

The JDK is the Java Development Kit, which is a full-featured Java SDK. It has everything the JRE has, as well as a compiler (Javac) and tools (such as Javadoc and JDB). It can create and compile programs.

JRE is the Java runtime environment. It is the collection of everything you need to run a compiled Java program, including the Java Virtual Machine (JVM), Java class libraries, Java commands, and other basic artifacts. However, it cannot be used to create new programs.

If you just want to run a Java program, you just need to install the JRE. If you need to do some Java programming, you’ll need to install the JDK. However, this is not absolute. Sometimes, even if you don’t plan on doing any Java development on your computer, you still need to install the JDK. For example, if you deploy a Web application using JSPS, you are technically just running Java programs in the application server. So why do you need the JDK? Because the application server converts JSPS into Java servlets, you need to use JDK to compile the servlets.

4. Oracle JDK vs. OpenJDK

There are probably a lot of people like me who haven’t touched or used OpenJDK before looking at this question. So are there any major differences between Oracle and OpenJDK? Here are some information I collected to answer this question that many people ignore.

For Java 7, there is nothing critical. The OpenJDK project is based on HotSpot source code donated by Sun. In addition, OpenJDK was selected as the reference implementation for Java 7, maintained by Oracle engineers. An Oracle blog post from 2012 has a more detailed answer about the differences between the JVM, JDK, JRE and OpenJDK:

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

A: Very close – Our Oracle JDK version build process is based on OpenJDK 7, adding only a few parts, such as deployment code, which includes Oracle’s Java plug-in and implementation of Java WebStart, as well as some closed source party components such as graphical rasterizers, Some open source third-party components, such as Rhino, and bits and pieces, such as additional documentation or third-party fonts. Going forward, our goal is to open source all parts of the Oracle JDK, except the parts where we consider commercial functionality.

Conclusion:

  1. Oracle JDK versions will be released every three years, while OpenJDK versions will be released every three months;

  2. The OpenJDK is a reference model and is fully open source, whereas the Oracle JDK is an implementation of OpenJDK and is not fully open source;

  3. The Oracle JDK is more stable than the OpenJDK. The OpenJDK and Oracle JDK have nearly the same code, but the Oracle JDK has more classes and some bug fixes. Therefore, if you want to develop enterprise/business software, I recommend you choose the Oracle JDK because it is thoroughly tested and stable. In some cases, some people have mentioned that they may encounter many application crashes while using OpenJDK, but simply switch to the Oracle JDK to solve the problem;

  4. The Oracle JDK provides better performance than the OpenJDK in terms of responsiveness and JVM performance;

  5. The Oracle JDK does not provide long-term support for upcoming releases; users must update to the latest version each time to get support;

  6. The Oracle JDK is licensed under the binary code License, while the OpenJDK is licensed under the GPL V2 license.

5. The difference between Java and C++

I know many people have never learned C++, but the interviewer likes to compare Java with C++. No way!! Even if you haven’t learned C++, write it down!

  • Both are object-oriented languages that support encapsulation, inheritance, and polymorphism

  • Java does not provide Pointers to access memory directly; program memory is more secure

  • Java classes are single inheritance, C++ supports multiple inheritance; Although Java classes cannot be multiinherited, interfaces can.

  • Java has automatic memory management mechanisms that do not require programmers to manually free unwanted memory

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

A program can have more than one class, but only one class can be the main class. In A Java application, this main class is the class that contains the main () method. In Java applets, the main class is a subclass that descends from the system class JApplet or Applet. The main class of the application is not required to be public, but the main class of the applet must be public. 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 starts from the main thread (the main() method). Applets do not have a main method, but instead run embedded in a browser page (init() or run() is invoked), similar to flash mini-games.

8. Difference between character constants and string constants

  1. Form: A character constant is a single character caused by a single quotation mark. A string constant is several characters caused by a double quotation mark

  2. A string constant represents an address value (where the string is stored in memory).

  3. A string constant is a number of bytes (at least one end-of-character flag).

Ideas for Java Programming 4th edition: Section 2.2.2

9. Whether Constructor Constructor can be overridden

When we talk about inheritance we know that the private attributes and constructors of the parent class cannot be inherited, so Constructor cannot be overridden, but can overload, so you can see multiple constructors in a class.

10. Difference between overloading and overwriting

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

Overwrite: occurs in the parent class, the method name, parameter list must be the same, the return value range is less than or equal to the parent class, the exception range is less than or equal to the parent class, access modifier range is greater than or equal to the parent class; If the superclass method access modifier is private, the subclass cannot override the method.

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

encapsulation

Encapsulation privatized the properties of an object while providing 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 do not need to provide methods to access them. But if a class has no methods to access from the outside world, then that class is meaningless.

inheritance

Inheritance is the technique of using 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, but can not selectively inherit the parent class. Using inheritance makes it very easy to reuse old code.

Here are three things to remember about inheritance:

  1. Subclasses have properties and methods that are not private from their parent class.

  2. Subclasses can have their own attributes and methods, that is, they can extend their parent class.

  3. Subclasses can implement the methods of their parent class in their own way. (More on that later).

polymorphism

So-called polymorphism is refers to the procedures defined in the reference variable is pointing to the specific type and referenced by the variable from method calls are not sure when programming, but during the program is run to determine, that is, a reference variable will point to which class instance of the object, the reference variable from method calls the method to realize exactly is which class, It must be decided during the running of the program.

Polymorphism can be implemented in Java in two forms: inheritance (overwriting the same method by multiple subclasses) and interfaces (implementing the interface and overwriting the same method in the interface).

What is the difference between a StringBuffer and a StringBuilder

variability

Simply put: The String class uses final keyword character arrays to hold strings, privateFinalCharValue [], so strings are immutable. AbstractStringBuilder and StringBuffer both inherit from AbstractStringBuilder classes, AbstractStringBuilder also uses character arrays to hold the string char[]value without the final keyword, so both objects are mutable.

AbstractStringBuilder constructor AbstractStringBuilder constructor AbstractStringBuilder constructor AbstractStringBuilder constructor

AbstractStringBuilder.java

abstract class AbstractStringBuilder implements Appendable, CharSequence {
    char[] value;
    int count;
    AbstractStringBuilder() {
    }
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
Copy the code

Thread safety

Objects in strings are immutable, which means they are considered constants, thread-safe. AbstractStringBuilder AbstractStringBuilder is a common parent of StringBuilder and StringBuffer. AbstractStringBuilder defines some basic string operations, such as expandCapacity, Append, insert, indexOf and other public methods. StringBuffer places synchronization locks on methods or on invoked methods, so it is thread-safe. StringBuilder does not lock methods synchronously-so it is not thread-safe.

performance

Each time a String type is changed, a new String is generated and a pointer is pointed to the new String. A StringBuffer operates on the StringBuffer object itself each time, rather than generating new objects and changing object references. Using StringBuilder in the same situation yields only 10% to 15% performance improvement over using StringBuffer, but at the risk of multithreading insecurity.

Summary of the use of the three:

  1. Operate on a small amount of data = String

  2. Single thread manipulation of large amounts of data in string buffer = StringBuilder

  3. Multithreaded manipulation of large amounts of data in string buffers = StringBuffer

13. Automatic packing and unpacking

Boxing: Wrapping base types with their corresponding reference types;

Unpacking: convert packaging type to basic data type;

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

Because static methods can be called without an object, other non-static variables cannot be called in a static method, nor can members of a non-static variable be accessed.

15. The role of defining a do-nothing, no-arguments constructor in Java

If a Java program calls a superclass-specific constructor without super() before executing a subclass constructor, it will call the “no-arguments constructor” in the superclass. Therefore, if only the constructor with arguments is defined in the parent class and no super() is used to call the specific constructor in the parent class in the constructor of the child class, an error will occur at compile time because the Java program will not find a constructor without arguments in the parent class to execute. The solution is to add a constructor to the parent class that does nothing and takes no arguments.

What is the difference between import Java and Javax

At the beginning, the packages required for Java apis were Java-starting packages, and Javax was only used to extend API packages. Over time, however, Javax has expanded to become part of the Java API. However, moving extensions from the Javax package to the Java package would be too cumbersome and would end up breaking a bunch of existing code. Therefore, it was ultimately decided that the Javax package would become part of the standard API.

So, there’s really no difference between Java and Javax. It’s all one name.

What is the difference between an interface and an abstract class

  1. The default method of an interface is public, all methods can have no implementation in the interface (Java 8 starts with interface methods having default implementations), and abstract classes can have non-abstract methods

  2. Instance variables in interfaces are final by default, but not necessarily in abstract classes

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

  4. A class that implements an interface must implement all the methods of the interface, not necessarily an abstract class

  5. Interfaces can not be instantiated with new, but can be declared, but must reference an object to implement the interface from the design level, abstraction is the abstraction of class, is a template design, interface is the abstraction of behavior, is a behavior specification.

Note: In JDK8, interfaces can also define static methods that can be called directly with the interface name. Implementation classes and implementations are not callable. If two interfaces define the same default method, they must be overridden or an error will be reported. (see issue:https://github.com/Snailclimb/JavaGuide/issues/146)

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

  1. Syntactically, a member variable belongs to a class, while a local variable is a variable defined in a method or a method parameter. Member variables can be modified by modifiers such as public,private, and static, while local variables cannot be modified by access-control modifiers or static. However, both member variables and local variables can be modified by final;

  2. If a variable is static, it belongs to the class. If a variable is not static, it belongs to the instance. Objects live in heap memory and local variables live in stack memory

  3. From the variable in memory survival time: the member variable is a part of the object, it exists with the creation of the object, and the local variable with the method call and automatically disappear.

  4. If no initial value is assigned to a member variable, it is automatically assigned to the default value of the type (except that final modified member variables must be explicitly assigned). Local variables are not automatically assigned.

19. What operator is used to create an object? How is an object entity different from an object reference?

The new operator creates the object instance (which is in heap memory) and the object reference points to the object instance (which is in stack memory). An object reference can point to zero or one object (a string can be tied to either a balloon or a balloon); An object can have n references to it (a balloon can be tied with n strings).

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

The return value of a method is the result of executing code in a method body. (provided that the method is likely to produce results). Return value: receives the result so that it can be used for other operations!

21. What does a class constructor do if a class does not declare a constructor, does the program execute correctly? Why is that?

The main function is to complete the initialization of the class object. Yes. Because a class will have a default constructor that takes no arguments even if it does not declare a constructor.

22. What are the properties of the constructor

  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. Automatically executed when an object of the class is generated, no call required.

23. What is the difference between static and instance methods

  1. You can use the “class name” when calling static methods externally. Method name, or object name. Method name “. Instance methods have only the latter. That is, you can call a static method without creating an object.

  2. When a static method accesses a member of the class, it only allows access to a static member (that is, static member variables and static methods), but not to instance member variables and instance methods. Instance methods do not have this limitation.

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

The equality of objects compares whether the contents in memory are equal. Reference equality, on the other hand, compares whether the memory addresses they point to are equal.

The subclass constructor with no arguments is called before the subclass constructor is called.

Help subclasses do initialization work.

26. == equals(important)

== : This is used to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object. (Base data type == compares values, reference data type == compares memory addresses)

Equals () : Also checks whether two objects are equal. But it is generally used in two ways:

  • Case 1: The class does not override equals(). Comparing two objects of that class through equals() is equivalent to comparing them through “==”.

  • Case 2: The class overrides equals(). In general, we override equals() to make the contents of two objects equal; Return true if their contents are equal (that is, the objects are considered equal).

Here’s an example:

public class test1 {
    public static void main(String[] args) {
        String a = new String("ab"); B = new String()"ab"); // b is another reference, with the same content as String aa ="ab"; // Put it in the constant pool String bb ="ab"; // Search from the constant poolif (aa == bb) // true
            System.out.println("aa==bb");
        if (a == b) // false, different object system.out.println ("a==b");
        if (a.equals(b)) // true
            System.out.println("aEQb");
        if(42 == 42.0) {//true
            System.out.println("true"); }}}Copy the code

Description:

  • The equals method on String is overridden, because the equals method on object compares the memory addresses of objects, while the equals method on String compares the values of objects.

  • 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 object to be created, and assigns it to the current reference if it does. If not, create a new String in the constant pool.

27. HashCode and Equals (Important)

The interviewer may ask you, “Have you overridden hashcode and equals? Why do you have to override hashCode to override equals?”

Introduction to hashCode ()

HashCode () is used to get a hashCode, also known as a hashCode; It actually returns an int. The purpose of this hash code is to determine the index position of the object in the hash table. HashCode () is defined in the JDK’s Object.java, which means that any class in Java contains a hashCode() function.

Hash table stores key-value pairs. It can quickly retrieve the corresponding value according to the key. That’s where the hash code comes in! (Can quickly find the desired object)

Why hashCode

Let’s use “how a HashSet checks for duplicates” as an example of why hashCode is needed:

When you add an object to a HashSet, the HashSet evaluates the object’s Hashcode value to determine where the object was added. It also compares the object’s Hashcode value to the hashcode value of other objects that have already been added. If there is no matching Hashcode, the HashSet assumes that the object is not repeated. But if objects with the same Hashcode value are found, the equals () method is called to check whether objects with hashCode equality are really the same. If they are the same, the HashSet will not let the join succeed. If it is different, it will be rehashed to another location. (From the second edition of my Java primer, Head First Java). This significantly reduced the number of equals calls, which in turn significantly increased the execution speed.

HashCode () and equals ()

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

  2. If two objects are equal, calling equals on both objects returns true

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

  4. Therefore, if equals is overridden, hashCode must be overridden as well

  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 never be equal anyway (even if they point to the same data)

28. Why is there only value passing in Java

https://github.com/Snailclimb/JavaGuide/blob/master/EssentialContentForInterview/MostCommonJavaInterviewQuestions/ the first week (20 The 18-8-7). The md

29. 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 produce multiple threads during its execution. Unlike a process, many threads of the same kind share the same memory space and a group of system resources, so the system is much less burden than a process when producing a thread or switching between threads. It is also because of this, threads are also called lightweight processes.

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

Process is a process of program execution, is the basic unit of the system running program, so the process is dynamic. When a system runs a program, it is a process from creation, to execution, to extinction. In simple terms, a process is a program in execution, which executes instruction after instruction in the computer. At the same time, each process also occupies certain system resources such as CPU time, memory space, files, files, I/O device access, and so on. In other words, when a program is executed, it is loaded into memory by the operating system. Threads are smaller running units that processes are divided into. The main difference between threads and processes is that processes are essentially independent, whereas threads are not necessarily, as threads in the same process will most likely interact with each other. On the other hand, a process belongs to the category of operating system, mainly in the same period of time, can execute more than one program, while a thread is in the same program almost simultaneously execute more than one program segment.

30. What are the basic states of threads?

A Java thread can only be in one of six different states at a given time in its running life (figure in Section 4.1.4, Art of Concurrent Programming in Java).

Threads are not fixed in one state during their life cycle but switch between states as the code executes. Java thread state transitions are shown below (from Section 4.1.4 of The Art of Concurrent Programming in Java) :

As can be seen from the figure above:

When the thread is created, it will be in the NEW state, and when the start() method is called, it will start running, and the thread will be in the READY state. A runnable thread is in the RUNNING state after it has acquired a CPU timeslice.

The operating system hides RUNNABLE and RUNNING states in the Java Virtual Machine (JVM), and it only sees RUNNABLE states. Java Thread Life Cycle and Thread States), so Java systems generally refer to these two States collectively as RUNNABLE States.

After executing wait(), the thread enters the state of WAITING. A thread in a waiting state needs to be notified by another thread before it can return to the running state, and a TIME_WAITING state adds a timeout limit to the waiting state. For example, a Java thread can be placed in a TIMED WAITING state using either the sleep (Longmillis) or wait (Longmillis) methods. When the timeout expires, the Java thread will return to the RUNNABLE state. When a thread calls a synchronous method, it enters a BLOCKED state without acquiring the lock. Threads TERMINATED after executing Runnable’s run() method.

31 Summary of the final keyword

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

  1. For a final variable, if it is of a primitive data type, its value cannot be changed once initialized; If a variable is a reference type, it cannot be made to point to another object after it is initialized.

  2. When you modify a class with final, it indicates that the class cannot be inherited. All member methods ina final class are implicitly specified as final methods.

  3. There are two reasons to use the final method. The first reason is to lock the method in case any inherited classes change its meaning. The second reason is efficiency. In earlier Versions of Java implementations, final methods were converted to inline calls. But if the method is too large, you may not see any performance gains from inline calls (these optimizations with final methods are no longer required in current Java versions). All private methods ina class are implicitly specified as final.

32 Exception handling in Java

Java exception class hierarchy diagram

In Java, all exceptions have a common ancestor in the java.lang packageThrowable class. Throwable: There are two important subclasses:ExceptionError (Error), both are important subclasses of Java exception handling, each containing a large number of subclasses.

Error: An Error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with what the code writer is doing, and instead represent problems with the JVM (Java Virtual Machine) while the code is running. For example, a Java Virtual Machine run error, an OutOfMemoryError occurs when the JVM no longer has the memory resources it needs to continue with the operation. When these exceptions occur, the Java Virtual Machine (JVM) typically selects thread termination.

These errors indicate that the fault occurs on the VM itself or when the VM tries to execute an application, such as a Java Virtual Machine running error or a NoClassDefFoundError. These errors are not detectable because they are outside the control and processing capabilities of the application, and most of them are not allowed to occur while the program is running. Even if an error does occur, a properly designed application should not, by nature, attempt to handle the exception it raises. In Java, errors are described by subclasses of Error.

Exception: An Exception that can be handled by the program itself. The Exception class has an important subclass, RuntimeException. RuntimeException is thrown by the Java VIRTUAL machine. NullPointerException (thrown when the variable to be accessed does not reference any object), ArithmeticException (dividing an integer by 0, Put the exception) and ArrayIndexOutOfBoundsException (subscript cross-border exception).

Note: The difference between exceptions and errors: exceptions can be handled by the program itself, and errors cannot be handled.

Common methods of the Throwable class

  • Public string getMessage(): Returns details about when an exception occurs

  • Public string toString(): Returns a brief description of when an exception occurs

  • Public string getLocalizedMessage(): Returns localization information for the exception object. Overriding this method with a subclass of Throwable can claim localized information. If the subclass does not override the method, the method returns the same information as getMessage ()

  • Public void printStackTrace(): Prints exception information encapsulated by Throwable objects on the console

Summary of Exception Handling

  • Try block: Used to catch exceptions. This may be followed by zero or more catch blocks, or if there is no catch block, a finally block must follow.

  • Catch block: Used to handle exceptions caught by a try.

  • Finally block: Statements ina finally block are executed whether or not exceptions are caught or handled. When a return statement is encountered ina try or catch block, the finally block is executed before the method returns.

A finally block is not executed in four special cases:

  1. An exception occurred on the first line of the finally block. Because on other lines, the finally block will still be executed

  2. System.exit(int) was used in the previous code to exit the program. Exit is a parameter function; If the statement follows an exception statement, finally is executed

  3. The thread on which the program resides dies.

  4. Close the CPU.

The following part from issue:https://github.com/Snailclimb/JavaGuide/issues/190.

About the return value:

If a try statement contains a return, it returns the value of the variable in the try block. The detailed execution process is as follows:

  1. If there is a return value, it is saved to a local variable;

  2. Execute JSR to finally statement;

  3. After the finally statement is executed, return the value previously saved in the local variable list.

  4. If both try and finally statements have returns, ignore the return of the try statement and use a finally return instead.

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

For variables that do not want to be serialized, use the TRANSIENT keyword modifier.

The transient keyword prevents serialization of variables in an instance that are modified with this keyword. When an object is deserialized, variable values modified transient are not persisted and restored. Transient can only modify variables, not classes and methods.

34 Get two common methods of keyboard input

Method 1: Use Scanner

Scanner input = new Scanner(System.in);
String s  = input.nextLine();
input.close();
Copy the code

Method 2: Through BufferedReader

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
String s = input.readLine(); 
Copy the code

reference

  • https://stackoverflow.com/questions/1906445/what-is-the-difference-between-jdk-and-jre

  • https://www.educba.com/oracle-vs-openjdk/

  • https://stackoverflow.com/questions/22358071/differences-between-oracle-jdk-and-openjdk?answertab=active#tab-top