preface

I found that a lot of programmers are well prepared before the interview, what difficult diseases, unsolved mysteries are ready to no problem, open mouth. Instead, Java is the easiest

Basic time, all kinds of overturned (may be that the basic content is too simple to spend energy), was able to get a higher salary, because the foundation did not answer well, by

Caught as an excuse and chopped several K, it is not worth the gain. So today I would like to share with you a summary and analysis of the Interview questions based on Java, so that we can better deal with

Interview, impact higher salary!



1. Why is the String class final

Mainly for “safety” and “efficiency” reasons, because:

1. Since the String class cannot be inherited, it is not unmodified, which avoids security risks caused by inheritance;

2, The String class appears in the program frequency is relatively high, if in order to avoid security risks, every time it appears with final modification, this will undoubtedly reduce the performance of the program

Rate, so simply set it to final one to improve efficiency;

2. HashMap source code, implementation principle, underlying structure.

A HashMap is a combination of arrays and linked lists. Each array element stores the first node of a linked list. In essence, it is an implementation of the hash table “zip method”.

The linked list element of a HashMap corresponds to a static internal class Entry, which mainly contains key, value and next elements

There are put and GET methods. The principle of PUT is to calculate index using hash% entry. length. In this case, Entry[index]= this element. If the index is the same

The new element is placed in the Entry[index]. The original element is called Entry[index].next

Get is easier, iterating through the array and then iterating over the list elements.

The NULL key is always placed in the first element of the Entry array

Method to resolve hash conflicts: chain address method

The rehash process is as follows: Determine that the capacity of the table exceeds the current capacity of the hash table and adjust the capacity of the table. If the capacity exceeds the maximum value, set to

Integer.Maxvalue

3. What are Java collection classes? Name a few Java collection classes you know.

The collection classes are stored in the java.util package.

The collection class stores the reference of the object rather than the object itself. For the convenience of expression, we call the object in the collection refer to the reference of the object in the collection.

There are three main types of sets: set, list, and map.

The Collection interface is divided into Collection and Map. List and set implement Collection interface

4. Describe the respective implementations and differences between ArrayList and LinkedList

ArrayList,LinkedList both implement the java.util.List interface,

  • ArrayList is a data structure based on dynamic arrays, and LinkedList is a data structure based on linked lists.
  • ArrayList feels superior to LinkedList for random access to GET and set because LinkedList moves the pointer.
  • For add and remove operations, LinedList has an advantage because ArrayList moves data.

5. What are the queues in Java and what are the differences

ConcurrentLinkedQueue, LinkedBlockingQueue, ConcurrentLinkedQueue

ArrayBlockingQueue and LinkedList.

About ConcurrentLinkedQueue and LinkedBlockingQueue:

  • LinkedBlockingQueue uses the lock mechanism and ConcurrentLinkedQueue uses the CAS algorithm, although the underlying LinkedBlockingQueue also uses the CAS algorithm to obtain the lock
  • ConcurrentLinkedQueue does not block fetching elements. LinkedBlockingQueue supports a blocking take() method. If you want the consumer of ConcurrentLinkedQueue to block, implement it yourself
  • In terms of insert element performance, ConcurrentLinkedQueue is definitely the fastest in terms of both literal and simple code analysis, but this depends on the specific test scenario. I did two simple demos to test it. The results are as follows. This is especially true on multi-CPU servers, where the difference between locked and unlocked queues is visible. ConcurrentLinkedQueue is much faster than LinkedBlockingQueue: ConcurrentLinkedQueuePerform: in the case of using ConcurrentLinkedQueue 100 threads circulation increase yuan prime number is: 33828193 LinkedBlockingQueuePerform: in the case of using LinkedBlockingQueue 100 threads circulation increase yuan prime number is: 33827382

6. The difference between class. forName and classloader in reflection

Both class. forName and classLoader can be used in Java to load classes.

In addition to loading the Class’s. Class file into the JVM, class.forname interprets the Class, executing the static block of the Class.

The classloader only does one thing: it loads a. Class file into the JVM. It does not execute static blocks, only newInstance.

Class. ForName (name,initialize,loader) also controls whether static blocks are loaded. And only the newInstance() method is invoked to create objects of the class using the call constructor.

7. New features of Java7 and Java8

The following features are of personal interest and are not complete. To learn more, do your own search for official documentation.

Java 7 features:

1. Switch case can use String (int and char); 2. Supports base 2 starting with 0B. Supports underscores in the middle of digits, which are automatically deleted during parsing. 3. Catch multiple exceptions at a time; Separated by |; 4. Try-with-resource: Enable a resource in a try. The system automatically closes the resource after the resource is used. 5. Map

> anagrams = new HashMap<>(); Anti-google Guava. 6. Collection classes can now be assigned and referenced like arrays in JS. List

list = [“item”]; String item = list[0]; Set

set = {“item”}; Map

map = {“key” : 1};
,>


,>

int value = map[“key”];

7. Moved the string constant pool from permgen to heap; Causing string.Intern () methods to behave inconsistently before and after 1.7;

Java8 features: 1. Lambda expressions; 2. Add stream, Date, Time, Base64 tool classes; 3. Metaspace is used to replace Permgen area with metaspace. 4. Class dependency analyzer: JDEPS, can take package, directory, folder as input, output dependencies, not found 5. JJS, can execute JavaScript code;

8. The operation efficiency of Java array and linked list, under which circumstances, which operation efficiency is high

Array is more efficient than linked list in randomly accessing data, randomly adding data and randomly deleting data. The smaller the data volume is, the smaller the efficiency gap between the two is, and the larger the data volume is, the larger the gap is.

We also welcome you to discuss all kinds of weird questions we finally get in the interview. We specially set up a Java technology exchange group: 895244712. We hope we can have a small circle of friends to join us and share some technical expertise from time to time.

9. Investigate and locate the problem of Java memory leak: the use of JMAP, JStack, etc

blog.csdn.net/sinat_29581…

10. The difference between String, StringBuilder and StringBuffer

There are two main differences between the three classes: speed and thread-safety.

  1. First, the speed, or execution speed, in this case: StringBuilder > StringBuffer > String

String is the slowest.

String is a String constant, while StringBuilder and StringBuffer are String variables, meaning that a String object cannot be changed once created, whereas the latter two objects are variables and can be changed.

2. Thread safety

In thread-safety, StringBuilder is thread-unsafe, whereas StringBuffer is thread-safe

If a StringBuffer object is used by multiple threads in the StringBuffer, many of the methods in StringBuffer can carry the synchronized keyword, which is thread-safe, but the methods in StringBuilder do not. There may be some wrong operations. So if the operation is multithreaded, use StringBuffer, but in single-threaded cases, the faster StringBuilder is recommended.

3. To sum up, String: Applies to a small number of String operations

StringBuilder: This is suitable for large operations in the character buffer under a single thread

StringBuffer: Applies to multiple threads where a large number of operations are performed in the character buffer

11. Differences between hashTable and HashMap

1. Storage structure

HashMap

HashTable

Array + linked list/red black tree

Array + linked list

HashMap storage rules:

Array storage is preferred. If Hash conflicts occur, the list will be stretched out of the array for storage (add at the end of the list). If the length of the list is greater than the set value, the list will be converted to a red-black tree.

HashTable storage rules:

Array storage is preferred. When storing elements, fetch the subscript element (which may be NULL) and add it to the next property of the array element Entry (added at the head of the list).

When a Hash conflict occurs, the new element next attribute points to the conflicting element. If there are no Hash conflicts, the next attribute of the new element is null

Description is a little vague, post the source code will be a little clearer:

Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
Copy the code

2. Expansion mode

HashMap

HashTable

oldCap * 2

oldCap * 2 + 1

3. About null values

HashMap

HashTable

Both key and value can be null

The key, the valueDon’tCan be null

4. Thread safety

HashMap HashTable
Thread insecurity Thread safety

13. Structure of exceptions, runtime and non-runtime exceptions

Da Shen’s explanation: blog.csdn.net/qq_27093465…

14. String a= “ABC” String B = “ABC” String C = new String(” ABC “) String D = “ab” + “C”. The result of the comparison between them using ==

Portal: blog.csdn.net/qq_36381855…

15. A common String method

The String class provides a large number of operations, as illustrated here13Kind of String class commonly used methods for your reference. The reference code is as follows:package cn.mc;
public class StringTestMc {
 private String str = "helloWorld";
 /** * turns the string into an array of characters */
 public void tocharyArry(a) {
  char c[] = str.toCharArray();
  for (int i = 0; i < c.length; i++) {
   System.out.println("Convert to array output :"+ c[i]); }}/** * retrieves the character */ at the specified position from the string
 public void tocharAt(a) {
  char c = str.charAt(3);
  System.out.println("Specify characters like:" + c);
 }
 /** * turns the string into a byte array */
 public void tobyte(a) {
  byte b[] = str.getBytes();
  System.out.println("Convert to byte array output:" + new String(b));
 }
 /** * gets the length of a string */
 public void tolength(a) {
  int l = str.length();
  System.out.println("The length of the string is:" + l);
 }
 /** * finds if a specified string exists, returns the position of the string, or -1 */ if not
 public void toindexOf(a) {
  int a1 = str.indexOf("e");// Find the position of the character e
  int a2 = str.indexOf("l".2);// find the position of l, starting with the third
  System.out.println("The position of E is: + a1);
  System.out.println(The position of l is: + a2);
 }
 /** * remove the left and right Spaces */ from the string
 public void totrim(a) {
  String str1 = " hello ";
  System.out.println("Output with left and right Spaces removed :" + str1.trim());
 }
 /** * string interception */
 public void tosubstring(a) {
  System.out.println("Truncated characters are:" + str.substring(0.3));// Cut the content from 0 to 3 positions
  System.out.println("Intercept from position 3:" + str.substring(2));// Start at position 3
 }
 /** * Splits the character according to the specified string. The split data is returned as an array of strings
 public void tosplit(a) {
  String s[] = str.split("e");// Press e in Hello to split the string
  for (int i = 0; i < s.length; i++) {
   System.out.println("Split result:"+ s[i]); }}/** * convert the string to case */
 public void tochange(a) {
  System.out.println("Converts \"hello\" to uppercase:" + str.toUpperCase());// Convert Hello to uppercase
  System.out.println("Converts \"HELLO\" to uppercase:"
    + str.toUpperCase().toLowerCase());// Convert HELLO to lowercase
 }
 /** * Determines whether to start or end with the specified string */
 public void tostartsWithOrendWith(a)
 {
  if(str.startsWith("he"))// Checks whether the string starts with he
  {
   System.out.println("String begins with he");
  }
  if(str.endsWith("lo"))
  {
   System.out.println("String ends in lo."); }}/** * Compare two String contents */
 public void toequals(a)
 {
  String str3="world";
  if(str.equals(str3))
  {
   System.out.println("These two strings are equal.");
  }
  else
   System.out.println("These two strings are not worth the same.");
 }
 /** * Two strings are compared case insensitive */
 public void toequalslgnoreCase(a)
 {
  String str4="HELLO";
  if(str.equalsIgnoreCase(str4))
  {
   System.out.println("Hello and Hello ignore case comparison value equal"); }}/** * replaces a specified string with another string */
 public void toreplaceAll(a)
 {
  String str5=str.replaceAll("l"."a");
  System.out.println("The result of substitution is:"+str5);
 }
 public static void main(String[] args) {
 StringTest obj = newStringTest(); obj.tocharyArry(); obj.tocharAt(); obj.tobyte(); obj.tolength(); obj.toindexOf(); obj.totrim(); obj.tosubstring(); obj.tosplit(); obj.tochange(); obj.tostartsWithOrendWith(); obj.toequals(); obj.toequalslgnoreCase(); obj.toreplaceAll(); }}Copy the code

16. What are the types of Java references

There is a class of objects that can be kept in memory when there is enough space. If memory space is still very tight after GC, these objects can be discarded. Many systems have caching capabilities suitable for this scenario, so after jdk1.2

Java divides references into four types: strong reference, soft reference, weak reference, and virtual reference.

  • Strong references: objects such as Object a=new Object() are never recycled.
  • SoftReference :SoftReference: when a memory overflow exception is about to occur, the system adds the object to the collection scope for recycling again. If the collection still has insufficient memory, an overflow exception is thrown.
  • Weak references: Weaker than soft references and will not survive the next GC. Whether or not the current memory is sufficient, the next GC will be reclaimed.
  • Virtual references: also known as phantom references, the weakest, the existence of a virtual reference to an object does not affect its lifetime, the only purpose is to receive a system notification after the object is reclaimed.

17. Distinction between abstract classes and interfaces

Interface is an open, there can be no private methods or variables inside, is used to let others use, and an abstract class can have a private method or private variable, in addition, implementing an interface must implement all methods defined in the interface, and implement an abstract class can selectively rewrite need method, general application, the top is the interface, Then comes the abstract class implementation interface, and finally the concrete class implementation. In addition, interfaces can implement multiple inheritance, whereas a class can only inherit one superclass, but multiple inheritance can be achieved by inheriting multiple interfaces, which also have functions such as identification (there are no methods in the interface, such as the Remote interface) and data sharing (variables in the interface are all constants).

18. Java base types and byte sizes

Java data type bytes represent ranges

Byte (byte) 1-128 to 127 Boolean (Boolean) 1 True or false short 2-32768 to 32767 CHAR 2 Specifies the number of integers corresponding to characters. The value ranges from 0 to 65535 int (integer) 4-2147483648 to 2147483647 Float 4-3.4E38-3.4E38 Double 8-1.7E308 to 1.7E308 Long 8 – 9223372036854775808 ~ 9223372036854775807

19. The Hashtable, HashMap, ConcurrentHashMap underlying implementation principle and thread safety

Here comes the great God again: blog.csdn.net/qq_27093465…

21. What about Hash conflicts? What are the ways to resolve hash conflicts?

The Hash algorithm resolves conflicts using the following methods

1. Open addressing method:

The so-called open addressing method is to look for the next empty hash address as soon as a conflict occurs. As long as the hash table is large enough, the empty hash address will always be found and the record will be saved

Fi (key) = (key)+di MOD m (di=1,2,3… ,m-1)

※ Open addressing resolves conflicts by using some sort of probe technique to form a sequence of probes in a hash table when a conflict occurs. Search cell by cell along the sequence until the given keyword is found, or

An open address is encountered (that is, the address unit is empty) until (if you want to insert, when the open address is detected, the new node to be inserted can be stored in the address unit). A table is indicated when an open address is detected during lookup

If no keyword is found, the search fails.

For example, our keyword set for,67,56,16,25,37,22,29,15,47,48,34 {12}, long table to 12. We use the hash function f of key = key mod l2

When calculating the first S number {12,67,56,16,25}, they are all hash addresses with no conflicts.



When key = 37 is calculated, f(37) = 1 is found, which conflicts with 25.

So we apply the formula f(37) = (f(37)+1) mod 12 = 2. So we store 37 at subscript 2:

2. Rehash: Rehash is also called double Hash. There are multiple different Hash functions. ., and wait for the hash function to calculate the address until there is no conflict. Although aggregation is not easy to occur, the calculation time is increased.

3. Chain address method:

The basic idea of chained address method is that each hash table node has a next pointer, and multiple hash table nodes can use the next pointer to form a one-way linked list, which can be used by multiple nodes assigned to the same index

Linked lists are joined, as in:

Key pair K2, v2 and key pair k1, v1 have index values of 2 after calculation, and then conflict occurs. However, the next pointer can be used to connect the nodes where K2 and k1 are located, so as to solve the problem of hash conflict



4. Establish public overflow area:

The basic idea of this method is to divide the hash table into two parts: basic table and overflow table. All elements that conflict with the basic table will be filled into the overflow table

22. How to rewrite the hashCode() and equals() algorithm

Reference address: blog.csdn.net/neosmith/ar…

conclusion

Well, today’s share is here, I hope to help the need to interview the tao friends smoothly. The profound question is to answer well, but the foundation can not fall, pay was cut to believe that it is not everyone hope to see, anyway, I have experienced, very uncomfortable, ha ha.