This article was adapted from: Lebyte

The article mainly explains: 2021Java knowledge points

For more information about 2021, you can follow the public account “LeByte” to send: 999**

1. Can a”.java” source file contain multiple classes (not inner classes)? What are the restrictions?

There can be more than one class, but only one public class, and the public class name must match the file name.

2, short s1= 1; s1= s1+1; Is that wrong?

S1 +1 will automatically promote the type, resulting in int. Assigning to s1 will report an error requiring a strong cast.

3, short s1= 1; s1 += 1; Is that wrong?

+= is a Java specified operator that is treated specially by the compiler so that it compiles correctly.

4. When you use the final keyword to modify a variable, the reference must not change.

With final variables, the reference variable (that is, the address) cannot be changed, and the contents of the object to which the reference variable points can still be changed

5. Can non-static methods be called from inside static methods? Why is that?

Can’t. Because non-static methods are associated with an object, you must create an object on which method calls can be made (object. Methods). Static method calls don’t need to create an object and can be called directly. If a call to a non-static method is made from a static method, to which object is that non-static method associated? The logic doesn’t hold.

6. The difference between Overload and Override?

Overload means that there can be multiple methods in the same class with the same name but with different argument lists (that is, different number or type of arguments).

Overriding Override means that a method in a subclass can have exactly the same name and parameters as a method in the parent class. When a subclass object calls this method, the defined method in the subclass will be called, overwriting the methods in the parent class. This is also a manifestation of polymorphism in object-oriented programming.

7. Can the Overloaded method change the return type?

If several Overloaded methods have different lists of arguments to the Overloaded Overloaded method, their return type can certainly be different.

If the argument lists of two methods are exactly the same, no matter whether the return values are the same, this is not allowed. It’s impossible to tell which method the programmer really wants to call, because they look exactly the same when called.

8. Is the interface inheritable? Does an abstract class implement an interface? Can abstract classes inherit concrete classes? Can an abstract class have a static main method?

Interfaces can inherit from interfaces. Abstract classes can implement interfaces, and abstract classes can inherit from concrete classes. Abstract classes can have static main methods.

Remember that the only differences between abstract classes and normal classes are that you cannot create instance objects and allow abstract methods.

9. What is the mechanism for implementing polymorphism in Java?

Depending on the parent class (or interface definition) reference variable can point to the child class (or concrete implementation class) instance object.

The methods called by the program are dynamically bound at runtime, referring to the specific instance object to which the variable points, rather than to the methods defined in the type of the variable.

What’s the difference between AbstractClass and interface?

Abstract classes can have constructors; interfaces cannot.

Abstract classes can have ordinary member variables, but interfaces do not

An abstract class can contain non-abstract ordinary methods, and all methods in an interface must be abstract, with no non-abstract ordinary methods.

Abstract methods in an abstract class can be of public or protected type. Abstract methods in an interface can only be of public type and default to public Abstract.

String s = “Hello”; s = s + “world!” ; Did the contents of the original String change after execution?

No. Because String is designed to be immutable, all of its objects are immutable. It’s just that S no longer refers to the old object.

String s=”a”+”b”+”c”+”d”;

Javac compilation can optimize expressions that add string constants directly to get the answer, rather than waiting until runtime to add

This line of code is optimized by the compiler at compile time to define a String of “abcd” directly, so the above code should only create a String object.

13. Final, finally, Finalize

Final is used to declare properties, methods, and classes, indicating that properties are immutable, methods are not overridden, and classes are not inherited, respectively.

Finally is part of the exception handling statement structure and means always execute.

Finalize is a method of the Object class that will be called when the garbage collector executes the collected Object.

14. What is the difference between error and exception?

Error represents a serious problem in cases where recovery is not impossible but difficult. Let’s say memory runs out. It is impossible to expect the program to handle such a situation. Exception indicates that the program can also overcome and recover from problems

15. What is the difference between stack and heap in Java? Stacks are often used to hold method frames and local variables, while objects are always allocated on the heap.

Stacks are typically smaller than the heap and are not shared between multiple threads, whereas the heap is shared by all threads across the entire JVM.

The stack: When a variable is defined in a block of code, Java allocates memory for that variable on the stack. When a variable is defined in a block of code, Java automatically releases the memory allocated for that variable. The memory space can be immediately repurposed.

Heap: Heap memory is used to hold objects and arrays created by new, and memory allocated in the heap is managed by the Java virtual machine’s automatic garbage collector.

Can int be cast to byte? In practice, we can cast without error.

However, it is common for large types to be converted to small types: ints are 32-bit, while byte is 8-bit. If cast, the upper 24 bits of ints will be discarded, so try not to do this.

17. What does hashCode do? What does it have to do with A. als(b)? The hash value of the object corresponding to the hashCode method. It is commonly used for hash-based collection classes such as Hashtable, HashMap, LinkedHashMap, and so on. According to the Java specification, two objects that use the equal() method to determine equality must have the same Hash code.

18. The advantages and principles of garbage recycling.

Garbage collection can effectively prevent memory leaks and efficiently use available memory. The garbage collector is typically run as a single low-level thread that can unpredictably clean and reclaim objects in the heap that have died or have not been used for a long time. The programmer cannot call the garbage collector in real time to collect an object or all objects. Collection mechanisms include generational replication garbage collection, tagged garbage collection, and incremental garbage collection.

Principle: You can add a referenced counter to an object to determine whether it is already referenceless. But it is difficult to solve the circular reference problem.

Set obj1-reference and obj2-Reference to null if necessary. The two pieces of memory in the Java heap remain references to each other and cannot be reclaimed.

Reachability analysis: Through a series of ‘GC Roots’ objects as starting points, the path from these nodes is called the reference chain. An object is unavailable when there is no reference link to GC Roots.

Is there a memory leak in Java

Memory leak: An object or variable that is no longer being used by a program remains in memory. Java has a garbage collection mechanism that ensures that when objects are no longer referenced, they are automatically removed from memory by the garbage collector.

Because Java uses a directed graph for garbage collection management, it eliminates the problem of reference loops, such as two objects that refer to each other and can be reclaimed as long as they are unreachable from the root process.

Memory leaks in Java: Memory leaks are most likely to occur when long-lived objects hold references to short-lived objects.

Memory leaks occur in Java when a long-lived object cannot be reclaimed because it holds a reference to it, even though it is no longer needed. In layman’s terms, it is possible for a programmer to create an object and never use it again, but the object is always referenced, that is, the object is useless but cannot be collected by the garbage collector. This is how memory leaks can occur in Java, for example, in a caching system, We load an object into the cache (in a global map object, for example) and then never use it again. The object is always referenced by the cache but never used again.

 

What is the difference between a thread and a process?

Processes are the basic unit of operating system resource allocation, while threads are the basic unit of task scheduling and execution

Threads are a subset of processes, and a process can have many threads, each performing different tasks in parallel.

Different processes use different memory space, and all threads share the same memory space.

22. How to implement threads in Java?

Class extends Thread{public void run(){public static void main(String[] args){Thread thread = new Handler(); // Create thread object thread.start(); {public void run(){public void run(){public void run(){public void run()} public static void main(String[]) args){ Handler handler = new Handler(); Thread thread = new Thread(handler); // Create thread object thread.start(); // Start thread}} 23, Java keyword volatile and synchronized;

1. Volatile The variables it modifies do not keep copies, but access main memory directly. In the Java memory model, there is main Memory, and each thread has its own memory (such as registers).

For performance, a thread keeps a copy of the variable to be accessed in its own memory. In this case, the value of the same variable in memory in one thread may be inconsistent with the value in memory in another thread or in main memory at any given moment.

Declaring a variable volatile means that it is subject to modification by other threads and therefore cannot be cached in thread memory. 2, the synchronized

When it is used to decorate a method or a code block, it ensures that at most one thread is executing the code at a time.

When two concurrent threads access the synchronized(this) block of the same object, only one thread can be executed at a time.

2. When a thread accesses a synchronized(this) block of an object, another thread can still access the non-synchronized (this) block of the object.

3. In particular, when one thread accesses a synchronized(this) block in an object, access to all synchronized(this) blocks in an object is blocked by other threads.

Thread life cycle?

When a New thread is created, its state is New. When we call the thread’s start() method, the state is changed to Runnable. The thread scheduler allocates CPU time to the threads in the Runnable thread pool and changes their state to Running. Other thread states include Waiting, Blocked, and Dead.

25. Deadlock?

A deadlock in which processes compete for resources and are unable to move forward without external action.

The reasons can be summed up in two aspects: competing resources and the necessary conditions for deadlock to be generated illegally in inter-process advance order:

Mutually exclusive condition: A resource is occupied by only one process at a time. Request and hold conditions: Hold on to acquired resources. No deprivation condition: acquired resources can only be released by oneself. Loop waiting condition: there is a loop chain of processes – resources.

What is a thread pool? Why use it?

Threads are expensive to create in terms of resources and time, the response time can be slow if the task comes in, and the number of threads a process can create is limited.

Thread pool realizes thread reuse and saves time and resources.

Public ThreadPoolExecutor(int corePoolSize, int corePoolSize, int corePoolSize, int corePoolSize, int corePoolSize, int corePoolSize, int corePoolSize Long keepAliveTime, TimeUnit Unit, // The idle time of a thread exceeding corePoolSize, // The idle time of a thread exceeding corePoolSize is discarded. BlockingQueue workQueue, ThreadFactory ThreadFactory, RejectedExecutionHandler handler) // Reject the policy.

The JAVA reflection mechanism allows you to know all the properties and methods of any entity class in the running state; For any object, you can call any of its methods and properties; This ability to dynamically retrieve information and invoke object methods is called the Reflection mechanism of the Java language.

What are the differences and connections between JDK, JRE and JVM?

JVM: A Java VM. The ability to identify bytecode instructions in class files and call the operating system up to the API to complete the action. So the JVM is at the heart of Java’s ability to cross platforms.

JRE: The Java runtime environment. Contains two parts, some basic libraries for the JVM and Java.

JDK: Java development kit. The JDK is the core of Java development, integrating the JRE and some handy gadgets.

The relationship of the three is: a layer of nested relationships. The JDK > JRE > JVM.

29. Deep copy shallow copy

Data types fall into two basic types and reference types:

Basic types: Basic types like Number, String, Boolean, etc. Reference types: Object and Array

A shallow copy simply copies the reference address of an object. Two objects point to the same memory address. If you change any value, the other value will change

A deep copy is a copy of an object and its value from one object to the other.

30. What are the parts of JVM memory? What does each part do?

The JVM memory area is divided into five parts: heap, method area, virtual machine stack, local method stack, and program counter.

1) pile.

The heap is the storage area for Java objects, any Java object instances and arrays allocated with new fields. 2) Method area.

It is used to store information about classes that have been loaded by the virtual machine, constants, static variables, and code compiled by the just-in-time compiler. The method area has been removed from the JDK1.8 permanent generation. 3) Virtual machine stack.

For each method executed in the virtual machine stack, a stack frame is created to store information about local variables, operand stacks, dynamic links, method exits, and so on. 4) Local method stack.

Similar to the role played by the virtual machine stack, the virtual machine stack serves the Java method, while the local method stack serves the Native method used by the virtual machine. When executing each local method, a stack frame will be created to store information such as local variable table, operand stack, dynamic link, method exit and so on. 5) Program counter.

Indicates the next bytecode instruction to be executed by the Java virtual machine.

The virtual machine stack, local method stack, and PC registers are owned independently by each thread and are not shared with other threads.

31. Why 4.0-3.6=0.40000001?

The decimal in base 2 cannot accurately express the decimal in base 10. In the process of calculating the decimal in base 10, we must first convert it to base 2 for calculation, which causes errors in the process.

32, What does “==” compare?

The “==” sides are objects that compare addresses.

“==” is flanked by basic types that compare values.

Thank you for your recognition and support, xiaobian will continue to forward “LeByte” quality articles