Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the back-end test questions of the latest version of Java in 2021?

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what are the back-end test questions of the latest version of 2021 Java". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. please follow the editor's train of thought to study and learn what are the back-end test questions of the latest version of 2021 Java.

1. Object oriented

Compared with process-oriented, there are two different ways to deal with the problem.

Process-oriented pays more attention to every step and sequence of things, while object-oriented pays more attention to what participants (objects) there are and what they need to do.

For example: washing machine washing clothes

Process-oriented will disassemble the task into a series of steps (functions): 1, turn on the washing machine-> 2, put clothes-> 3, put detergent-> 4, clean-> 5, and dry

Object-oriented will detach the human object and the washing machine object:

Person: turn on the washing machine to put clothes and detergent

Washing machine: cleaning and drying

From the above examples, we can see that process-oriented is more direct and efficient, while object-oriented is easier to reuse, expand and maintain.

object-oriented

Encapsulation: the meaning of encapsulation is to clearly identify all member functions and data items that are allowed to be used externally

The internal details are transparent to external calls, and external calls do not need to be modified or care about the internal implementation.

(1) the attributes of javabean are private and provide external access to getset, because the assignment or acquisition logic of attributes can only be determined by javabean itself. It cannot be arbitrarily modified by the outside.

Private String name;public void setName (String name) {this.name = "tuling_" + name;} the name has its own naming rules, which obviously cannot be assigned directly from the outside.

(2), orm framework

To operate the database, we don't need to care about how the link is established and how the sql is executed, we just need to introduce mybatis and adjust the method.

Inheritance: inherit the methods of the base class and make your own changes and / or extensions

The methods or properties common to the subclass directly use those of the parent class, instead of redefining it yourself, you just need to extend your own personalized

Polymorphism: based on the class to which the object belongs, the external calls to the same method actually execute different logic.

Inheritance, method override, parent class reference to subclass object

Parent class type variable name = new subclass object; variable name. Method name ()

Unable to call functions specific to subclasses

2 、 JDK 、 JRE 、 JVMJDK:

Java Develpment Kit java development tools

JRE:

Java Runtime Environment java Runtime Environment

JVM:

Java Virtual Machine java virtual machine

3. Compare with equals

= = the values in the stack are compared, the basic data type is the variable value, and the reference type is the address of the memory object in the heap

The = = comparison is also used by default in equals:object, which is usually rewritten

Object

Public Boolean equals (Object obj) {return (this = = obj);}

String

Public Boolean equals (Object anObject) {if (this = = anObject) {return true;} if (anObject instanceof String) {String anotherString = (String) anObject; int n = value.length; if (n = = anotherString.value.length) {char v1 [] = value Char v2 [] = anotherString.value; int I = 0; while (NMI -! = 0) {if (v1 [I]! = v2 [I]) return false; iTunes + } return true;}} return false;}

As you can see from the above code, the overridden equals () method in the String class is actually comparing the contents of two strings.

Public class StringDemo {public static void main (String args []) {String str1 = "Hello"; String str2 = new String ("Hello"); String str3 = str2; / / reference passing System.out.println (str1 = = str2); / / false System.out.println (str1 = = str3) / / false System.out.println (str2 = = str3); / / true System.out.println (str1.equals (str2)); / / true System.out.println (str1.equals (str3)); / / true System.out.println (str2.equals (str3)) / / true}} 4. Introduction to hashCode and equalshashCode:

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

The hash table stores key-value pairs (key-value), which is characterized by the ability to quickly retrieve the corresponding "value" according to the "key". This is the use of hash codes! (you can find the object you need quickly)

Why should there be hashCode:

Take how HashSet checks for duplicates as an example to illustrate why there is a hashCode:

When an object joins the HashSet, HashSet first calculates the hashcode value of the object to determine the position in which the object is added to see whether the position has a value. If not, HashSet will assume that the object does not repeat. But if a value is found, the equals () method is called to check whether the two objects are really the same. If the two are the same, HashSet will not let it join successfully. If it is different, it will be hashed back to another location. In this way, the number of equals is greatly reduced, and the execution speed is greatly improved.

(1) if two objects are equal, then hashcode must also be the same.

(2) two objects are equal. Calling the equals method on both objects returns true.

(3) two objects have the same hashcode value, and they are not necessarily equal.

(4) therefore, if the equals method is overwritten, then the hashCode method must also be overwritten.

(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 they point to the same data)

5 、 final

Final

Modifier class: indicates that the class is not inheritable

Modification method: indicates that the method cannot be overridden by subclasses, but can be overloaded

Modifier variable: indicates that once a variable is assigned, its value cannot be changed.

(1) modify member variables

If final modifies class variables, you can only specify initial values in static initialization blocks or when declaring such variables. If final modifies a member variable, you can execute the initial value in a non-static initialization block, declare the variable, or in the constructor.

(2) modify local variables

The system does not initialize local variables, which must be displayed and initialized by the programmer. So when you use final to modify a local variable, you can specify the default value at definition time (the later code can no longer assign a value to the variable), or you can not specify the default value, and assign the initial value to the final variable in the later code (only once)

Public class FinalVar {final static int a = 0; / / you need to assign a value or static code block assignment / * * static {a = 0;} * / final int b = 0; / / when you declare again, you need to assign a value or assign a value in the code block or constructor assignment / * {b = 0 } * / public static void main (String [] args) {final int localA; / / local variables only declare that they are not initialized, will not report an error, and have nothing to do with final. LocalA = 0; / / be sure to assign / / localA = 1 before use; but the second assignment}} (3) modify basic type data and reference type data

If it is a variable of a basic data type, its value cannot be changed once initialized; if it is a variable of a reference type, it cannot point to another object after initialization. But the referenced value is variable.

Public class FinalReferenceTest {public static void main () {final int [] iArr= {1 final int [] 4}; iArr [2] =-3; / / legal iArr=null; / / illegal, final Person p = new Person (25) cannot be reassigned to iArr; p.setAge (24) / / legal pendant null; / / illegal}}

Why can local inner classes and anonymous inner classes only access local final variables?

After compilation, two class files are generated, Test.class Test1.class

Public class Test {public static void main (String [] args) {} / / the local final variable aforme b public void test (final int b) {/ / jdk8 is optimized here, no need to write, grammatical sugar, but actually there are, and final int a = 10 cannot be modified. / / Anonymous inner class new Thread () {public void run () {System.out.println (a); System.out.println (b);} } .start ();}} class OutClass {private int age = 12; public void outPrint (final int x) {class InClass {public void InPrint () {System.out.println (x) System.out.println (age);}} new InClass (). InPrint ();}

The first thing to know is that the inner class and the outer class are at the same level, and the inner class will not be destroyed as the method finishes execution just because it is defined in the method.

There is a problem here: when the method of the outer class ends, the local variable is destroyed, but the inner class object may still exist (it will die only if no one references it again). There is a contradiction here: the inner class object accesses a variable that does not exist. To solve this problem, a copy of the local variable is copied as a member variable of the inner class, so that when the local variable dies, the inner class can still access it, actually accessing the "copy" of the local variable. This is like prolonging the life cycle of local variables.

When copying a local variable into a member variable of an inner class, we must ensure that the two variables are the same, that is, if we modify the member variable in the inner class, the local variable in the method has to change accordingly, how to solve the problem?

Set the local variable to final, after initializing it, I will not let you modify this variable, which ensures the consistency of the member variables of the inner class and the local variables of the method. This is actually a compromise. Make the local variable consistent with the copy established within the inner class.

6 、 String 、 StringBuffer 、 StringBuilder

String is modified by final and is immutable. Each operation produces a new String object.

Both StringBuffer and StringBuilder operate on the original object

StringBuffer is thread-safe, StringBuilder is not thread-safe

StringBuffer methods are all modified by synchronized.

Performance: StringBuilder > StringBuffer > String

Scenario: use the last two when you often need to change the contents of a string

StringBuilder is preferred, and StringBuffer is used when multithreading uses shared variables.

7. The difference between overloading and rewriting:

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 the access modifier can be different, occur at compile time.

Rewrite:

Occurs in the parent-child class, the method name and parameter list must be the same, the return value range is less than or equal to the parent class, the exception range thrown is less than or equal to the parent class, and the access modifier range is greater than or equal to the parent class; if the parent method access modifier is private, the subclass cannot override the method.

Public int add (int aline string b) public String add (int a dint string b) / / compile error 8, the difference between interface and abstract class

(1) ordinary member functions can exist in an abstract class, but only public abstract methods can exist in an interface.

(2) the member variables in the abstract class can be of various types, while the member variables in the interface can only be of public static final type.

(3) Abstract classes can only inherit one, and interfaces can implement multiple.

The interface is designed to constrain the behavior of the class (more accurately, a "have" constraint, because the interface cannot specify what the class cannot do), that is, to provide a mechanism to force different classes to have the same behavior. It only restricts whether the behavior exists or not, but it does not restrict how to implement the behavior.

Abstract classes are designed for code reuse. When different classes have some identical behaviors (marked as behavior set A), and some of them are implemented in the same way (a non-true subset of A, marked as B), these classes can be derived from an abstract class. B is implemented in this abstract class to avoid all subclasses to implement B, which achieves the goal of code reuse. The part of A minus B is left to each subclass to implement on its own. It is precisely because AmurB is not implemented here that abstract classes are not allowed to be instantiated (otherwise, they cannot be executed when called to Amurb).

An abstract class is an abstraction of the nature of a class, expressing the relationship of is a, such as BMW is a Car. The abstract class contains and implements the general characteristics of the subclass, abstracts the differential characteristics of the subclass, and leaves it to the subclass to implement.

The interface is the abstraction of the behavior and expresses the relationship of like a. For example: Bird like an Aircraft (can fly like an aircraft), but it is essentially is a Bird. The core of the interface is to define the behavior, that is, what the implementation class can do. As for who the main body of the implementation class is and how it is implemented, the interface does not care.

Usage scenarios: when you focus on the nature of something, use abstract classes; when you focus on an operation, use interfaces.

Abstract classes are far more functional than interfaces, but it is expensive to define abstract classes. Because in high-level languages (and actually designed) each class can inherit only one class. In this class, you must inherit or write all the commonalities of all its subclasses. Although the interface is much weaker in function, it is only a description of an action. And you can implement multiple interfaces in a class at the same time. The difficulty will be reduced in the design phase.

9. The difference between List and Set List

Orderly, save objects in the order in which they enter, repeatable, allow multiple Null element objects, use Iterator to fetch all elements, iterate through them one by one, and use get (int index) to get the elements of the specified subscript

Set

Unordered and non-repeatable. A maximum of one Null element object is allowed. When fetching elements, you can only use the Iterator API to get all the elements, traversing each element one by one.

10. The difference between ArrayList and LinkedList ArrayList:

Based on dynamic array, continuous memory storage, suitable for subscript access (random access), expansion mechanism: because the length of the array is fixed, it is necessary to create a new array when the length of the data is exceeded, and then copy the data of the old array to the new array. If the data is not inserted at the tail, it will also involve the movement of elements (make a copy later, insert new elements) Using tail interpolation and specifying initial capacity can greatly improve performance, even exceeding linkedList (you need to create a large number of node objects)

LinkedList:

Based on linked list, can be stored in scattered memory, suitable for data insertion and deletion operations, not suitable for query: need to go through one by one

Traversing the LinkedList must use iterator, not the for loop, because every time the body of the for loop gets an element through get (I), it needs to re-traverse the list, which is extremely performance-intensive.

In addition, do not try to use indexOf and other return element index, and use it to traverse, use indexlOf to traverse the list, when the result is empty, it will traverse the entire list.

11. What's the difference between HashMap and HashTable? What is the underlying implementation? Difference:

(1) HashMap method has no synchronized modification, thread is not safe, and HashTable is thread safe.

(2) HashMap allows key and value to be null, but HashTable does not

Underlying implementation: array + linked list implementation

Jdk8 starts the linked list height to 8, the array length exceeds 64, the linked list is transformed into a red-black tree, and the elements exist as internal class Node nodes.

(1) calculate the hash value of key, then hash the length of the array and correspond to the array subscript.

(2) if there is no hash conflict (there are no elements in the subscript position), create a Node and store it in the array directly.

(3) if there is a hash conflict, make an equal comparison first. If the same is the same, the element will be replaced. If it is different, the linked list height will be inserted into the linked list. If the linked list height reaches 8, the array length will be changed into a red-black tree when the length is 64, and if the length is less than 6, the red-black tree will be turned back to the linked list.

(4) key is null, and the location array with subscript 0 is expanded.

12. The principle of ConcurrentHashMap, the difference between jdk7 and jdk8 versions jdk7:

Data structure: ReentrantLock+Segment+HashEntry, an Segment contains an HashEntry array, and each HashEntry is a linked list structure

Element query: the second hash, the first time Hash locates to Segment, the second time Hash locates to the head of the linked list where the element is located

Lock: Segment segmented lock Segment inherits ReentrantLock and locks the Segment of the operation. Other Segment is not affected, and the concurrency is the number of segment. It can be specified by constructor. Array expansion will not affect other segment.

The get method does not need to be locked and is guaranteed by volatile

Jdk8:

Data structure: synchronized+CAS+Node+ red-black tree, Node val and next are decorated with volatile to ensure visibility

Find, replace, and assign operations all use CAS

Lock: lock the head node of the linked list, which does not affect the read and write of other elements. The lock granularity is finer and more efficient. When expanding, it blocks all read and write operations and concurrent expansion.

The read operation is unlocked:

The val and next of Node are decorated with volatile, and the reader thread modifies the mutually visible array of the variable with volatile to ensure that the read thread is aware of the expansion.

13. What is a bytecode? What are the benefits of using bytecode? Compilers and interpreters in Java:

The concept of virtual machine is introduced in Java, that is, a virtual machine is added between the machine and the compiler. This virtual machine provides a common interface to the compiler on any platform.

The compiler only needs to face the virtual machine, generate the code that the virtual machine can understand, and then the interpreter converts the virtual machine code into the machine code of a specific system. In Java, this code for virtual machines to understand is called bytecode (that is, files with a .class extension), and it is not targeted at any particular processor, only for virtual machines.

The interpreter for each platform is different, but the virtual machine implemented is the same. After the Java source program is compiled by the compiler, the bytecode is interpreted and executed by the virtual machine. The virtual machine sends each bytecode to be executed to the interpreter, which translates it into machine code on a specific machine, and then runs on the specific machine. This explains the characteristics of the coexistence of compilation and interpretation of Java.

Java source code-> compiler-> jvm executable Java bytecode (virtual instruction)-> jvm---- > interpreter in jvm-> machine executable binary machine code-> program runs.

Benefits of using bytecode:

Java language solves the problem of low execution efficiency of traditional interpretive language to some extent by means of bytecode, while retaining the portability of interpretive language. Therefore, Java programs run efficiently, and because bytecode is not specific to a particular machine, Java programs do not need to be recompiled to run on many different computers.

14. Exception system in Java

All exceptions in Java come from the top-level parent class Throwable.

There are two subclasses Exception and Error under Throwable.

Error is an error that the program cannot handle, and once this error occurs, the program will be forced to stop running.

Exception does not cause the program to stop, which is divided into two parts: RunTimeException runtime exception and CheckedException check exception.

RunTimeException often occurs in the process of running the program, which will cause the current thread of the program to fail. CheckedException often occurs in the process of program compilation, which will cause the program compilation to fail.

15. Java class loader

JDK comes with three classloaders: bootstrap ClassLoader, ExtClassLoader, AppClassLoader.

BootStrapClassLoader is the parent class loader of ExtClassLoader and is responsible for loading jar packages and class files under% JAVA_HOME%lib by default.

ExtClassLoader is the parent class loader of AppClassLoader and is responsible for loading the jar package and class class under the% JAVA_HOME%/lib/ext folder.

AppClassLoader is the parent class of the custom class loader and is responsible for loading the class files under classpath. System classloader, thread context loader inherits ClassLoader to implement custom classloader

16. Parental entrustment model

Benefits of the parental delegation model:

Mainly for security, to prevent user-written classes from dynamically replacing some of Java's core classes, such as String. At the same time, it also avoids repeated loading of classes, because different classes are distinguished in JVM, not only according to the class name, the same class file loaded by different ClassLoader is two different classes.

17. How does GC judge that an object can be recycled

Reference counting method: each object has a reference count property, which adds a reference count plus 1, subtracts 1 when the reference is released, and can be recycled when the count is 0.

Reachability analysis: search downward from GC Roots, and the path taken by the search is called reference chain. When an object is not linked to the GCRoots by any reference chain, it is proved that the object is unavailable, and the virtual machine determines that it is recyclable.

In the reference counting method, it may appear that A refers to BBJ B and A, even if they are no longer in use, but because the cross-reference counter = 1 can never be recycled.

The objects of GC Roots are:

Objects referenced by JNI (commonly known as Native methods) in the local method stack of objects referenced by constants in the object method area referenced by class static properties in the object method area referenced in the virtual machine stack (local variables in stack frames)

The unreachable object in the reachability algorithm does not die immediately, and the object has a chance to save itself. It takes at least two marking processes for an object to be declared dead by the system: the first is to find out that there is no reference chain connected to GC Roots after reachability analysis, and the second is to determine whether the finalize () method needs to be executed in the Finalizer queue automatically established by the virtual machine.

When an object becomes (GC Roots) unreachable, GC determines whether the object overrides the finalize method, and if not, it is recycled directly. Otherwise, if the object has not executed the finalize method, it is placed in the F-Queue queue, and a low-priority thread executes the finalize method of the object in the queue. After the execution of the finalize method, GC will again determine whether the object is reachable, and if it is not reachable, it will recycle it. Otherwise, the object "resurrects" each object can only trigger the finalize () method once.

Because the finalize () method is expensive and uncertain, it is impossible to guarantee the calling order of each object, so it is not recommended to use it and it is recommended to forget it.

Thank you for your reading, the above is the "2021 latest version of Java back-end test questions what" the content, after the study of this article, I believe you on the latest version of 2021 Java back-end test questions have a deeper understanding of this question, the specific use of the need for you to practice and verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report