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)

Hot Topics

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Full screen layout can be achieved using Flexbox or Grid. The core is to make the minimum height of the page the viewport height (min-height:100vh); 2. Use flex:1 or grid-template-rows:auto1frauto to make the content area occupy the remaining space; 3. Set box-sizing:border-box to ensure that the margin does not exceed the container; 4. Optimize the mobile experience with responsive media query; this solution is compatible with good structure and is suitable for login pages, dashboards and other scenarios, and finally realizes a full screen page layout with vertical centering and full viewport.

Selecting the Java SpringBoot React technology stack can build stable and efficient full-stack web applications, suitable for small and medium-sized to large enterprise-level systems. 2. The backend uses SpringBoot to quickly build RESTfulAPI. The core components include SpringWeb, SpringDataJPA, SpringSecurity, Lombok and Swagger. The front-end separation is achieved through @RestController returning JSON data. 3. The front-end uses React (in conjunction with Vite or CreateReactApp) to develop a responsive interface, uses Axios to call the back-end API, and ReactRouter

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi
