Summary of Java Interview Questions (End of Basic Interview Questions, 2020-10-13)

1. What is Iterator?

In order to conveniently process the elements in the collection, an object appears in Java. This object provides some methods to deal with the elements in the collection. For example, delete and get the elements in the collection. This object is called an iterator.

2. How to use Iterator? What are the characteristics?

Methods in the Iterator interface source code:

  1. The java.lang.Iterable interface is inherited by the java.util.Collection interface. The iterator() method of the java.util.Collection interface returns an Iterator object
  2. next() method to get the next element in the collection
  3. hasNext() Check if there are any elements in the collection
  4. The remove() method deletes the newly returned element of the iterator

3. What is the difference between Iterator and ListIterator?

1. ListIterator inherits Iterator

2. ListIterator has more methods than Iterator

  • add(E e) insert the specified element into the list, the insertion position is before the current position of the iterator
  • set(E e) The last element returned by the iterator replaces the parameter e
  • hasPrevious() The current position of the iterator, whether the collection contains elements in reverse traversal
  • previous() The current position of the iterator, traverse the collection in reverse, and the next element
  • previousIndex() The current position of the iterator, traverse the collection in reverse, and return the index of the next element
  • nextIndex() The current position of the iterator, returns the index of the next element

3. The scope of use is different, Iterator can iterate all collections; ListIterator can only be used for List and its subclasses

  • ListIterator has an add method, which can add objects to List; Iterator cannot
  • ListIterator has hasPrevious() and previous() methods, which can realize reverse traversal; Iterator cannot
  • ListIterator has nextIndex() and previousIndex() methods, which can locate the current index position; Iterator cannot
  • ListIterator has a set() method, which can modify List; Iterator can only be traversed, not modified.

4. How to ensure that a collection cannot be modified?

We can easily think of using final keywords to modify, we all know

The final keyword can modify classes, methods, and member variables. Final modified classes cannot be inherited. Final modified methods cannot be overridden. Final modified member variables must be initialized. If this member variable is a basic data type, it means this variable. The value of is immutable. If the member variable is a reference type, it means that the address value of the reference cannot be changed, but the content of the object pointed to by the reference can still be changed
.

So, how do we ensure that a collection cannot be modified? First of all, we must be clear that collections (map, set, list...) are all reference types, so if we use final modification, the contents of the collection can still be modified.

We can do an experiment:

It can be seen that we have defined a map collection with the final keyword. At this time, we pass values ​​into the collection, the first key-value pair is 1, 1; after we modify it, we can change the value of key 1 to 100, Explain that we can modify the value of the map collection.

So what should we do to ensure that the collection is not modified?
We can use the unmodifiableMap method under the Collections package. The map returned by this method cannot be modified. He will report java.lang.UnsupportedOperationException.

Similarly: Collections package also provides methods for list and set collections.
Collections.unmodifiableList(List)
Collections.unmodifiableSet(Set)

5. What are queues and stacks? What's the difference?

1. Queue first in first out, stack first in last out.

2. The speed of traversing data is different.

The stack can only fetch data from the head, and the first put it in need to traverse the entire stack before it can be taken out, and when traversing the data, a temporary space must be opened for the data to maintain the consistency of the data before the traversal;

The queue is different. It traverses based on the address pointer, and it can traverse from the beginning or the end, but it cannot be traversed at the same time. There is no need to open up temporary space, because the data structure is not imaged during the traversal process, and the speed is much faster.

6. What is Java's memory model?

Before understanding what the Java memory model is, let's first understand why the Java memory model is proposed.

As mentioned before, there are three major problems with concurrent programming

  • CPU cache, in the case of multi-core CPUs, brings visibility issues
  • The operating system's switching of the current execution thread brings about atomic problems
  • Translator instruction rearrangement optimization, which brings order problems

In order to solve the three major problems of concurrent programming, JSR-133 was proposed, the new Java memory model, and JDK 5 was used.

Brief summary

  • Java memory model is a specification of JVM
  • Defines the specification of shared memory read and write operations in multithreaded programs
  • Shields the access differences of various hardware and operating systems, and ensures that Java programs have consistent access to memory under various platforms
  • Ways to solve concurrency problems: limit processor optimization and use memory barriers
  • Enhanced the memory semantics of three synchronization primitives (synchronized, volatile, final)
  • Defines the happens-before rule

7. Since volatile can guarantee the visibility of variables between threads, does it mean that operations based on volatile variables are concurrently safe?

Volatile modified variables do not have the problem of consistency in the working memory of each thread (in the memory of each thread, volatile modified variables will also be inconsistent, but because the main memory will be refreshed before each use Data to the working memory, the execution engine can not see the inconsistency, so it can be considered that there is no inconsistency problem), but the operation of java is not an atomic operation, resulting in volatile is not thread-safe under concurrency.

8. Please talk about how ThreadLocal solves concurrency safety?

In java programs, there are two commonly used mechanisms to solve the problem of multi-thread concurrency. One is the sychronized method. Through the lock mechanism, when one thread executes, let another thread wait, which is the way of time for space to make multithreading Serial execution. The other way is the ThreadLocal way, which allows multiple threads to execute in parallel by creating thread local variables and changing space for time. The two methods have their own advantages and disadvantages, and are suitable for different scenarios, and should be selected according to different business scenarios.

    In the spring source code, ThreadLocal is used to manage connections. In many open source projects, ThreadLocal is often used to control multi-threaded concurrency. Because it is simple enough, we don’t need to care about thread safety issues because the variables are Specific to each thread.

9. Many people say that ThreadLocal should be used with caution. Talk about your understanding. What should I pay attention to when using ThreadLocal?

The ThreadLocal variable solves the problem of sharing variables in a single thread in a multi-threaded environment. It is maintained by a hash table named ThreadLocalMap (key is the name of the ThreadLocal variable, and value is the value of the ThreadLocal variable);

Pay attention to the following points when using:

  • The threadLocal variables between threads do not affect each other,
  • Use private final static for decoration to prevent memory leaks in multiple instances
  • After using in the thread pool environment, remove the threadLocal variable or set it to an initial value

10. What is XSS attack and how to avoid it?

xss (Cross Site Scripting), or cross-site scripting, is a computer security vulnerability commonly found in web applications. It refers to the execution of unexpected JS scripts when rendering the DOM tree on the user's browser, which causes a security problem.

XSS is to inject malicious executable scripts on the user side. If the server does not process the user's input, it will directly output the user's input to the browser, and then the browser will execute the user-injected script. Therefore, the core of XSS attacks is to parse the text information into JS scripts when the browser renders the DOM, which triggers JS script injection. Then the defense method of XSS attacks is based on browser rendering. As long as we use HTML encoding to encode the information that the browser needs to render, when the browser renders the DOM element, it will automatically decode the information that needs to be rendered and parse the above information into a string instead of a JS script. This is our defense against XSS attacks. Core idea.

Prevention:
1. Obtain user input instead of innerHtml, use innerText.
2. Filter user input, such as escaping & <> "'/ etc.;

11. What is a CSRF attack and how to avoid it?

Cross-site request forgery (English: Cross-site request forgery), also known as one-click attack or session riding, usually abbreviated as CSRF or XSRF, is a way of forcing users to perform unintentional execution on the currently logged-in web application The attack method of the operation. Compared with cross-site scripting (XSS), XSS uses the user's trust in the specified website, and CSRF uses the website's trust in the user's web browser.

1. Attack details

A cross-site request attack, simply put, is that the attacker uses some technical means to deceive the user’s browser to visit a website that he has authenticated and perform some operations (such as sending emails, sending messages, and even property operations such as transferring money and purchasing goods. ). Since the browser has been authenticated, the visited website will be considered as a real user operation and run. This takes advantage of a loophole in user authentication in the web: simple authentication can only guarantee that the request is sent from a user's browser, but cannot guarantee that the request itself is voluntarily sent by the user.

example

Suppose the URL address used by a bank to perform a transfer operation is as follows: http://www.examplebank.com/withdraw?account=AccoutName&amount=1000&for=PayeeName

Then, a malicious attacker can place the following code on another website: <img src="http://www.examplebank.com/withdraw?account=Alice&amount=1000&for=Badman">

If a user with an account named Alice visits a malicious site, and she has just visited a bank shortly before, and the login information has not expired, then she will lose 1,000 funds.

This malicious URL can take many forms and hide in many places on the web page. In addition, the attacker does not need to control the website where the malicious URL is placed. For example, he can hide this kind of address in forums, blogs and any other websites where users generate information. This means that if the server does not have appropriate defense measures, users are at risk of being attacked even if they visit familiar and trusted websites.

Through the example, it can be seen that the attacker cannot directly obtain the user's account control through the CSRF attack, nor can he directly steal any user information. What they can do is to trick the user's browser into operating on the user's behalf.

2. Defense measures

Check Referer field

There is a Referer field in the HTTP header, which is used to indicate which address the request comes from. When processing sensitive data requests, generally speaking, the Referer field should be located under the same domain name as the requested address. Take the above bank operation as an example, the Referer field address should usually be the web page address where the transfer button is located, and it should also be located under www.examplebank.com. If it is a request from a CSRF attack, the Referer field will be an address containing a malicious web address and will not be located under www.examplebank.com. At this time, the server can recognize the malicious visit.

This method is simple and easy to implement, the workload is low, and only one step of verification is needed at the key access point. But this method also has its limitations, because it completely relies on the browser to send the correct Referer field. Although the http protocol has clear regulations on the content of this field, it cannot guarantee the specific implementation of the visiting browser, nor can it guarantee that the browser does not have security loopholes affecting this field. And there is also the possibility of attackers attacking some browsers and tampering with its Referer field.

3. Add verification token

Since the essence of CSRF is that the attacker deceives the user to visit the address set by himself, if it is required to request the user's browser to provide data that is not stored in the cookie when accessing sensitive data requests, and the attacker cannot forge data as verification, then the attack Those who can no longer run CSRF attacks. This kind of data is usually a data item in a form. The server generates and attaches it to the form, and its content is a pseudo-random number. When the client submits a request through the form, this pseudo-random number is also submitted for verification. During normal access, the client browser can correctly obtain and return this pseudo-random number. In a deceptive attack through CSRF, the attacker has no way of knowing the value of this pseudo-random number in advance, and the server will be due to the correction. Verify that the value of the token is empty or wrong, and reject the suspicious request.

12. How to achieve cross-domain? Tell me about the principle of JSONP implementation?

1. Detailed explanation of jsonp principle-finally figure out what jsonp is

2. The most popular cross-domain solution cors

Cors is the current mainstream cross-domain solution. Cross-domain resource sharing (CORS) is a mechanism that uses additional HTTP headers to tell the browser to allow web applications running on an origin (domain) to be allowed to access from different sources The specified resource on the server. When a resource requests a resource from a different domain, protocol, or port from the server where the resource itself is located, the resource initiates a cross-domain HTTP request.

3. Nginx, the most convenient cross-domain solution

Nginx is an extremely powerful web server, its advantages are lightweight, fast startup, and high concurrency.

Now nginx is almost the first choice in new projects. The services we develop with node or java usually need to go through the reverse proxy of nginx.

The principle of reverse proxy is very simple, that is, all client requests must be processed by nginx first, nginx acts as a proxy server and then forwards the request to the node or java service, thus avoiding the same-origin policy.

13. In Java, when to use overloading and when to use rewriting?

1. Overloading is a concentrated manifestation of polymorphism. In a class, when different types of data are to be processed in a unified way, overloading can be used.

2. The use of rewriting is based on the inheritance relationship. On the basis of inheriting the parent class, the subclass adds new functions and can be rewritten.

3. Simple summary:
overloading is diversity, rewriting is an enhancer; the
purpose is to improve the diversity and robustness of the program, to adapt to different scenarios, use overloading to expand; the
purpose is to not modify the original method and When extending or enhancing the method based on the source code, use rewrite;
life example:
if you want to eat a bowl of noodles, I provide you with ramen, fried noodles, sliced ​​noodles, and Dandan noodles for your choice. This is overloaded;
you If I want to eat a bowl of noodles, I not only brought you noodles, but also added vegetables and eggs. This is a rewrite;
design pattern:
cglib realizes dynamic proxy, and the core principle uses method rewriting;
details Answer:
 The most important application scenario of java overload is the overload of the constructor. After the constructor is overloaded, it provides a variety of parameter forms of the constructor, which can respond to different business needs and strengthen the robustness and robustness of the program. Extensibility, such as the ClassPathXmlApplicationContext in the Spring source code we recently learned. Its constructor uses overloading to provide a total of 10 constructors, which provides multiple options for business choices. When applied to the method, it is mainly to enhance the robustness and scalability of the method, such as the various tool classes we commonly use in development, such as the SMS tool class SMSUtil in my current work, and the method of sending text messages will be used Overloading, providing SMS sending methods for different formal parameters in different business scenarios, which improves the scalability and robustness of tool classes.
Summary: Overloading must modify the formal parameter list of the method (constructor), the return value type of the method, and the exception information of the method, that is, the access authority; the scope of use is in the same class, and the purpose is to modify the method ( Constructor) for functional expansion to cope with different usage requirements of multiple business scenarios. Improve the robustness and scalability of the program.
 Java override is only used to extend or modify the method of the parent class by the subclass, but in our development, in order to avoid program confusion, the rewrite is generally for the expansion of the method, such as the dynamic proxy implemented in cglib. , The proxy class inherits the target class, rewrites the method of the target class, and weaves aspects before and after the method.
Summary: When the method is rewritten, the parameter list and return value type must not be modified. Exceptions can be reduced or deleted, but new exceptions or broader exceptions cannot be thrown. The access rights of the method can be reduced, but cannot be changed. Strict restrictions.

4. In the Richter substitution principle, try not to rewrite and overload the methods of the subclass to the parent class. (We can use final means to enforce compliance)

14. Give examples to illustrate when you would prefer to use abstract classes instead of interfaces?

Both interfaces and abstract classes follow the design principle of "interface-oriented rather than implementation coding", which can increase the flexibility of the code and adapt to changing needs. Here are a few points to help you answer this question: In Java, you can only inherit one class, but you can implement multiple interfaces. So once you inherit a class, you lose the opportunity to inherit other classes.

Interfaces are usually used to represent subsidiary descriptions or behaviors such as: Runnable, Clonable, Serializable, etc., so when you use abstract classes to represent behavior, your class cannot be Runnable and Clonable at the same time (Note: This means if The case of implementing Runnable as an abstract class), because you cannot inherit two classes in Java, but when you use interfaces, your class can have multiple different behaviors at the same time.

In some time-critical applications, abstract classes tend to be used, which are slightly faster than interfaces. If you want to standardize a series of behaviors in the class inheritance hierarchy, and can better code in the same place, then abstract classes are a better choice. Sometimes, interfaces and abstract classes can be used together. Functions are defined in interfaces and default implementations are defined in abstract classes.

 

Previous post: Summary of Java Interview Questions (Out of Order Edition, 2020-09-29)

Next: Summary of Java interview questions (with answers)

Guess you like

Origin blog.csdn.net/guorui_java/article/details/109043769