The 8 most common mistakes in Java interview questions
1. Usage of static and final
The role of static can be discussed from three aspects, namely static variables, static methods, static kind.
Static variables: Static variables declared as static are essentially global variables. When an object is declared, a copy of the static variable is not generated, but all instance variables of the class share the same A static variable. In other words, this static variable is only loaded once and only a piece of storage space is allocated.
Static methods: Static methods declared as static have the following characteristics:
(1) Static methods can only call static methods;
(2) Static methods can only access static data;
(3) Static methods cannot reference this or super in any way;
Static class: Usually an ordinary class Declaration as static is not allowed, only an inner class is allowed (the main method is a typical example). At this time, the declared static class can be used directly as a normal class without the need to instantiate an external class.
The role of final can be understood from three aspects: variables, methods, and classes:
The value of the variable modified by final cannot be modified and is a constant;
The value of the variable modified by final Methods cannot be overridden;
final-modified classes cannot be inherited;
2. The difference between abstract classes and interfaces. Can a class inherit multiple classes? Can an interface inherit multiple classes? An interface? Can a class implement multiple interfaces?
Neither abstract classes nor interfaces can be instantiated directly. If they are to be instantiated, abstract class variables must point to subclass objects that implement all abstract methods, and interface variables must point to class objects that implement all interface methods.
Abstract classes must be inherited by subclasses, and interfaces must be implemented by classes.
Interfaces can only make method declarations. Method declarations can be made in abstract classes, and method implementations can also be made.
The variables defined in the interface can only be public static constants. In abstract classes, Variables are ordinary variables.
All abstract methods in an abstract class must be implemented by the subclass. If the subclass cannot implement all the abstract methods of the parent class, then the subclass can only be an abstract class. Similarly, when a class implements an interface, if it cannot implement all interface methods, then the class can only be an abstract class.
Abstract methods can only be declared, not implemented. abstract void abc(); cannot be written as abstract void abc(){}.
There can be no abstract methods in abstract classes.
If there is an abstract method in a class, then the class can only be an abstract class.
Abstract methods must be implemented, so they cannot be static or private.
Interfaces can inherit interfaces and multiple interfaces, but classes can only inherit from a single root.
3. Functions and usage of this and super
#this:
(1) Can access except the constructor method All properties and methods are called through this.
(2) Cannot be used in static methods
(3) Use this (parameter list) in the constructor to call Other construction methods of this class must be placed in the first sentence of the construction method.
super: Access the methods and properties of the parent class
(1) Access the methods and properties of the parent class;
(2) In the constructor The constructor of the parent class is called through super (parameter list), which must be placed in the first line of the constructor of the subclass.
4. What is the difference between final, finally, finalize?
final: The modifier (keyword) has three uses: If a class is declared as final, it means It cannot derive new subclasses, that is, it cannot be inherited. Declaring variables as final ensures that they will not be changed during use. Variables declared as final can only be read and cannot be modified in references after initialization. Methods declared as final can also only be used and cannot be overridden in subclasses.
finally: Usually placed after try...catch, the structure always executes the code block, which means that no matter whether the program is executed normally or an exception occurs, the code here can be executed as long as the JVM is not closed, and the external code can be released The resource code is written in the finally block.
finalize: A method defined in the Object class. Java allows the use of the finalize() method to do necessary cleanup work before the garbage collector clears the object from memory. This method is called by the garbage collector when it destroys an object. By overriding the finalize() method, you can organize system resources or perform other cleanup work.
5. What is the difference between Error and Exception?
Error represents system-level errors and exceptions that the program does not need to handle. It is a situation where recovery is not impossible but difficult. A serious problem; such as memory overflow, it is impossible to expect the program to handle such a situation;
Exception represents an exception that needs to be caught or needs to be handled by the program, which is a design or implementation problem; that is to say , which represents a situation that would never occur if the program were running normally.
6. Tell the life cycle of Servlet and the difference between Servlet and CGI.
After the Servlet is instantiated by the server, the container runs its init method, and when the request arrives, it runs its service method. The service method automatically dispatches the doXXX method (doGet, doPost) corresponding to the request, etc., when the server decides to destroy the instance. Call its destroy() method.
The difference with CGI is that Servlet is in the server process. It runs its service method through multi-threading. One instance can serve multiple requests, and its instance is generally not destroyed, while CGI processes each request. Both generate new processes and destroy the service after it is completed, so the efficiency is lower than Servlet.
7. How to prevent cache avalanche?
Cause:
Cache avalanche may be because the data is not loaded into the cache, or the cache fails in a large area at the same time, causing all requests to go Query the database, causing the database CPU and memory load to be too high, or even downtime.
Corresponding solution:
Use lock counting, or use a reasonable number of queues to avoid causing too much pressure on the database when the cache fails. Although this method can relieve the pressure on the database, it also reduces the throughput of the system.
Analyze user behavior and try to distribute failure time points evenly. Avoid cache avalanches.
If a certain cache server is down, you can consider primary and backup, such as redis primary and backup. However, double caching involves update transactions, and update may read dirty data, which needs to be solved.
8. Talk about your understanding of MVC
MVC is the abbreviation of Model-View-Controler. That is model-view-controller. MVC is a design pattern that enforces separation of input, processing, and output of an application.
The models, views, and controllers in MVC are responsible for different tasks.
View: A view is the interface that users see and interact with. Views display relevant data to the user and accept input from the user. Views do not perform any business logic processing.
Model: Model represents business data and business processing, equivalent to JavaBean. A model can provide data to multiple views. This improves application reusability.
Controller: When the user clicks the submit button in the Web page, the controller accepts the request and calls the corresponding model to process the request, and then calls the corresponding view to display the processing results based on the processing results.
MVC processing process: First, the controller accepts the user's request, calls the corresponding model for business processing, and returns data to the controller. The controller calls the corresponding view to display the processing results. and presented to the user through views.
The above is the detailed content of The 8 most common mistakes in Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time
![LOL Game Settings Not Saving After Closing [FIXED]](https://img.php.cn/upload/article/001/431/639/175597664176545.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.
!['Java is not recognized' Error in CMD [3 Simple Steps]](https://img.php.cn/upload/article/001/431/639/175588500160220.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.
