preface
2021, presumably everyone has the idea that wants to jump ship to rise salary, so certainly must have some preparation cough up, the first interview question must brush, followed by some other speech and behavior attention, these are secondly, the most important is still technology and not stage fright!! Be confident!! Let’s get to the point. Today, I’m going to share with you some questions that are frequently asked in Java interviews. I hope they can help you
Recently, I have organized my personal study notes into PDF documents, which mainly include Java foundation, data structure, JVM, multi-threading, Spring series family bucket, etc., including: MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, Spring Boot, Spring Cloud, RabbitMQ, Kafka, Linux, etc.
The article directories
Java Basics – Basics
Java Basics – Collections framework/generics/containers
Java basics – Multithreading
Java Basics – Framework Basics: Annotations/reflection/pop frameworks
Java Basics – Object-oriented: Inheritance/polymorphism/encapsulation
Java Basics – Design patterns
Java Basics — JVM/ class loading
Java base – I/O
Network programming and networking
The database
The operating system
The data structure
Java Basics – Basics
One, the size of the eight basic data types, and their encapsulation classes.
Byte (1 byte), short(Short) 2 ,int(Integer) 4 ,long(Long) 8 ,float(Float) 4 ,double(Double)8,boolean(Boolean),char(Character)2
Can Switch use string as parameter?
The variable types in switch statements can be byte, short, int, or char. We can use String from JDk1.7, which is determined by converting String to int in string. hashcode in switch.
Equals ==
The equals () operator is used to compare the values of two variables to whether they are equal, i.e. whether they are stored at the same location in memory. The equals () method is inherited from the String class and is used to check whether the contents of two objects are the same.
String s=new String(‘ xyz ‘); How many objects are created?
Creates a String variable s. If the “xyz” literal does not appear before the class is loaded here, loading here creates a String constant object corresponding to “xyz”. On a compliant JVM, execution of the new keyword at this point creates a String.
What are the common methods of Object?
Clone () returns a copy of this object
Equals () 2
Getclass () returns the running class of Object
4. Hashcode () returns the hash value of the object
5. Notify () wakes up a single process waiting for an object listener
NotifyAll () wakes up all processes that are waiting for the object listener
7. Wait () causes the current thread to wait until another thread calls notify() or notifyAll() of the object.
ToString () returns a string representation of this object
The garbage collector calls this method when the garbage collection determines that the object is not needed
Six, Java four kinds of references, weak and weak soft virtual, used in the scene.
Strong references: The garbage collector does not collect
Soft references: If there is enough memory, the garbage collector will not collect, and if there is not enough memory, the garbage collector will collect
Weak references: Once an object with only weak references is found, the garbage collector collects it.
Virtual references: If the object is found to have a virtual reference, the virtual reference is added to the reference queue associated with the object before it is reclaimed.
The difference between static variables and instance variables.
Static variables are preceded by the keyword static; instance variables are not.
An instance variable is a property that belongs to an object that must be created for the instance variable to be allocated space before it can be used. Static variables do not belong to any instance object, but to a class, also known as a class variable, and are allocated space as soon as the program loads the class’s bytecode without creating any instance objects. Static variables can be used without creating any objects, whereas instance variables need to create instance objects before they can be used.
Viii. Difference between Overload and Override
Overload indicates that there can be multiple methods with the same name in the same class, but the parameter lists of these methods are different, that is, the parameter parameters or parameter types are different. The return value can be different when overloaded, of course, but if the argument list is exactly the same, you can’t overload it by returning different types, which is not possible.
Override means that a method in a subclass can have exactly the same name and parameters as a method in the parent class. When the method is called from an object created by the subclass, the method defined in the subclass will be called. That is, the method in the subclass overrides the method in the parent class. A subclass overrides a parent class method by throwing fewer or smaller exceptions than the parent class. The return of an overridden method must be the same as that of the overridden method.
The difference between abstract classes and interfaces.
Abstract class can have the default method implemented, can have a constructor, can have the main method for running, can be directly added in the class implementation of the methods to implement interface without the default method, there is no constructor, could not use the main method for running, added to the interface method needs to be added in the concrete implementation of class methods.
A StringBuffer is a StringBuilder.
String means unmodifiable strings, StringBuffer means modifiable strings, String overrides equals () and hashCode () methods, and StringBuffer doesn’t override both. So StringBuffer objects have problems when stored in Java collection classes.
A StringBulider also represents a string whose content can be modified, but whose thread is not safe and runs efficiently.
The characteristics and meaning of Java object-oriented.
Encapsulation, inheritance, abstraction, polymorphism
1. Encapsulation: The purpose of encapsulation is to achieve “high cohesion and low coupling” of the program and prevent the changing influence of program interdependence. Encapsulation is the assurance that methods that operate on the same thing are in the same class as related methods, and that methods are in the same class as the data on which they operate.
2. Abstraction: Abstraction is to find out the similarities and commonalities of things, and then classify these things into the same category. This category only considers the similarities and commonalities of these things, ignoring the factors unrelated to the current topic.
3. Inheritance: Subclasses inherit the content of the parent class as their own content, and can add new content or modify the content of the parent class to better suit special needs. The reusability and expansibility of the program are improved.
4. Polymorphism: Polymorphism refers to the process defined in the reference points to a specific type and referenced by the variable from method calls are not sure when programming, but during the program is run to determine, that is, a reference variable STLL can point to which class instance object, the reference variable from method calls the method to realize exactly is which class, must can decide during the program is running.
Implementation of Java polymorphism
Interface implementation, inherit the parent class method rewrite,
Method overloading in the same class.
13, Error and exception
An error is a serious problem that may be difficult to recover from, and an exception that the program cannot handle is a design or implementation problem.
The difference between run-time exceptions and normal exceptions
Exceptions indicate abnormal conditions that may occur during the running of a program. A runtime exception is a common running error that may occur during common VM operations. The Java compiler requires methods to declare to throw possible non-runtime exceptions, but not exceptions that are not caught
15. Exception handling mechanism and simple principle and application in Java
When a JAVA program violates JAVA’s semantic rules, the JAVA virtual machine represents the error as an exception. There are two cases of semantic rule violations. One is semantic checking built into the JAVA class library. The array subscript crossing the line, for example, can cause IndexOutOfBoundsException; A NullPointerException is raised when a null object is accessed. On the other hand, JAVA allows programmers to extend this semantic checking by creating their own exceptions and choosing when to throw them with the throw keyword. All exceptions are subclasses of java.lang.Thowable.
Throws, throw, try catch finally represents what the meaning, try block can throw an exception?
Java handles exceptions through object-oriented methods, classifies all kinds of exceptions, and provides a good interface. In Java, each exception is an object that is an instance of the Throwable class or another subclass. When a
Method throws an exception object that contains information about the exception and can be caught and handled by the method that calls it. Java exception handling is implemented with five keywords: try, Catch, throw, throw, and finally. If an exception occurs, the system throws (throws) an exception. You can catch it by its type or finally handle it by the default handler.
Use try to specify a program that prevents all “exceptions”. Immediately after the try program, you should include a catch clause that specifies the type of “exception” you want to catch.
The throw statement is used to explicitly throw an “exception”.
Throws identifies the various “exceptions” that a member function may throw.
Finally To ensure that a piece of code is executed no matter what “exception” happens.
You can write a try statement outside a member function call and another try statement inside the member function to protect other code. Each time a try statement is encountered, the “exception” frame is put on the stack until all tries are complete. If the next level of try does not handle an “exception,” the stack expands until it encounters a try statement that does.
17, Try catch finally, try has a return, finally is executed?
1. Finally statements are always executed
2. If there is a return statement ina try or catch, and no return in finally, modifying data in finally except the wrapper type and static and global variables will have no effect on the variables returned in the try or catch.
3. Try not to use return statements in finally. If you do, the return statements in try and catch will be ignored, as well as the exceptions in try and catch.
4. Avoid throwing an exception in finally. If an exception occurs in finally, the code execution will throw an exception in finally
Java final, finally, and Finalize
Final is used to declare properties, methods, and classes, indicating that properties are immutable, methods are not overridden, and classes are not inherited, respectively.
For an inner class to access a local variable, the local variable must be defined as final, for example, a piece of code…
Finally is part of the exception handling statement structure and means always execute.
Finalize is a method of Object class. When garbage collector executes, Finalize will call the method of the Object to be collected, and can overwrite the method to provide other resource collection during garbage collection, such as closing files. The JVM does not guarantee that this method will always be called.
Common runtime exceptions
System exceptions are subclasses of RuntimeException. Common system exceptions are:
ArrayIndexOutOfBoundsException – an array access
ClassCastException – Type conversion exception
NullPointerException – An attempt to access an empty object’s variable, method, or element of an empty array
IllegalArgumentException – Method arguments are invalid
NoClassDefFoundException – The JAVA runtime system could not find the referenced class
Collection:
20. Structure of Collection framework
The Collection Framework broadly refers to several classes and interfaces of the java.util package. Such as Collection, List, ArrayList, and LinkedList, the Vector array) (to be automatic growth, HashSet, HashMap, etc.
Classes in the collection framework mainly encapsulate typical data structures, such as dynamic arrays, linked lists, stacks, collections, hash tables and so on.
The collection framework is similar to the utility classes often used in programming, allowing coding to focus on the implementation of the business layer without the need to implement the details – “encapsulation of data structures” and “implementation of typical algorithms” – from the bottom.
Xxi. Collection package structure
A Collection is the parent interface of a Collection class and is a single-column Collection. The main interfaces that inherit it are Set and List.
The subinterfaces of the Set interface are HashSet and TreeSet
The subinterfaces of the List interface are Arraylist, LinkedList, and Vector
The difference between Collection and Collection
A Collection is the parent interface of a Collection class. The interfaces that inherit it are Set and List
Collections is a helper class for the collection class, which provides a set of static methods for searching, sorting, thread-safe operations on Collections.
23. What interfaces should be implemented in Colection framework?
Comparable: Contains only the compareTo () method
Compare () equals ()
Map, Set, List, Queue, Stack
1. Maps are stored in the form of key-value pairs. The key is unique and cannot be repeated, while the value can be repeated. He has several concrete implementation classes, including Treemap, which is ordered, and HashMap, which is unordered.
2. List is ordered and repeatable
|–ArrayList
The underlying data structure is array, query fast, add and delete slow, thread insecurity, high efficiency
|–Vector
The underlying data structure is array, query fast, add and delete slow, thread insecurity, high efficiency
|–LinkedList
The underlying data structure is linked list, slow query, add and delete blocks, thread safety, low efficiency
3, the Set is out of order
|–HashSet
The underlying data structure is a hash table
How to ensure element uniqueness:
Relies on two methods, hashCode () and equals ()
|–LinkedHashSet
The underlying data structure is a linked list and a hash table. The linked list ensures the order of elements and the hash table ensures the uniqueness of elements
| – TreeSet the underlying data structure is a red-black tree,
How to ensure that elements are sorted:
Natural ordering: Make the classes to which elements belong implement the Comparable interface
Comparator sort: Lets the collection receive a Comparator implementation object
How to ensure element uniqueness:
Depending on whether the return value of the comparison is 0
The Query queue follows the first-in, first-out principle and does not allow null values to be inserted. The offer () method is recommended for adding elements and the poll () method is recommended for deleting elements
5. Stack follows the last-in, first-out principle and inherits from Vector. He extends the Vector class with five operations, which provide push and pop operations, as well as the peek () method to go to the stack vertices and test whether the stack is empty
6. Use method:
Lists are recommended for operations involving stacks, queues, etc
LinkedList is recommended for quick insertion and deletion of elements
An ArrayList is recommended for fast random access to elements
Elements in a Set cannot be repeated.
The elements in a Set are the only ones that can’t be repeated. Equals () is used to determine whether the elements are duplicated.
The equals () and == methods determine whether the reference values refer to the same object. Equals () is overridden in the class so that the contents and types of the two separated objects match, returning true.
Differences between HashMap and Hashtable.
1, Hashtable is based on the Dictionary class, and HashMap is an implementation class of the Map interface
Hashtable is thread-safe, i.e., synchronous; HashMap threads are not safe and are not synchronous.
3. A HashMap can have null values as keys or values
27. Differences between HashMap, LinkedHashMap and TreeMap.
1. HashMap stores data according to the hashcode value of the key. It can obtain its value directly according to the key, with fast access speed and completely random data
2. LinkedHashMap preserves the insertion order of records. When Iterator is used to iterate, the first data must be inserted first
3. TreeMap implements the SortMap interface, which can sort the records it saves by key. The default is ascending sort, or you can specify the sort comparator, so that the sorted records are returned when traversing.
Implementation of HashMap, LinkedHashMap, ConcurrentHashMap, ArrayList, LinkedList
1. A HashMap is a combination of two large structures in Java data structures: arrays and linked lists. The underlying array of a HashMap, in which each item is a linked list. The program first determines the Entry’s presence in the array based on the return value of the key’s Hashcode () method
If two entries have the same key, equals is called. If true is returned, the value of the original value is overridden. If false is returned, an Entry chain is formed at the head.
2. The underlying implementation of ArrrayList is array. When the ADD operation is performed, it will check whether the array size can accommodate new elements first. The original data is then copied into the new array.
3. LinkedList is a LinkedList at the bottom, whose implementation of add, delete, change and check is exactly the same as the operations in the data structure, and the insertion is orderly.
4. The underlying structure of LinkedHashMap is a double-linked list, and other logical processing is the same as HashMap. There is also no lock protection, and there are risks when using multiple threads.
5. ConcurrentHashMap consists of the segment array structure and the HashEntry array structure. The segment acts as a lock in the ConcurrentHashMap. The structure of a segment is an array and a linked list. A segment has a HashEntry, and each HashEntry is an element of a linked list. When modifying data in a HashEntry, you need to obtain its corresponding segment lock. Each ConcurrentHashMap has 16 segments by default.
Iterator Iterator
Iterator provides a unified interface for iterating through Collection elements. The Collection interface implements the Iterator interface. Each collection returns an instance of the Iterator () method and iterates over the elements. However, the Iterator method cannot be used to remove the elements while iterating over the elements. Otherwise, an exception will be thrown.
The difference between fail-fast and fail-safe.
Iterator’s security failure is based on making a copy of the underlying collection, so it is not affected by changes to the source collection. All collection classes under the util package fail quickly, and all classes under the util. Concurren package fail safely.
Java Basics – Collections framework/generics/containers
concept
Spring provides Container capabilities that manage the lifecycle of objects and their dependencies, using a configuration file (usually XML), Define the name of the object, how it is generated (Prototype or Singleton), which object must be generated as an attribute of an object, etc. Once the container is started, all objects can be used directly without writing a single line of code to generate the object. Or establishing dependencies between objects. To put it more bluntly: A container is a program written in Java that once had to write its own programs to manage object relationships, but now the container does it for you automatically. Commonly used container: WebSphere, WebLogic, Resin, Tomcat.
Container classes
Container class is actually a data structure used to store data. In JAVA, containers can be divided into “Set”, “List” and “Map”. As for why containers are needed, in general, they are difficult to scale in a storage structure that uses arrays as data, and the elements in arrays must be of the same type. Containers make up for both of these.
Java container classes include List, ArrayList, Vector, and Map, HashTable, and HashMap.
ArrayList and HashMap are asynchronous, Vector and HashTable are synchronous, so Vector and HashTable are thread-safe, whereas ArrayList and HashMap are not thread-safe. Vector and HashTable are less efficient than ArrayList and HashMap because synchronization takes machine time.
Second, the description of the set framework
All collection classes are located under the java.util package. Java’s Collection classes are derived primarily from two interfaces: Collection and Map, which are the root interfaces of the Java Collection framework, and which in turn contain subinterfaces or implementation classes.
1.Set, List and Map can be regarded as three categories of sets:
2. A List is an ordered set. The elements in a List can be repeated, and the elements in a List can be accessed according to their indexes.
A Set is an unordered Set. Elements in a Set cannot be repeated. Elements in a Set can only be accessed based on the elements themselves (which is why elements in a Set are not allowed to be repeated).
3. The Map contains key-value pairs of elements. Only the value of each element can be accessed according to its Key.
Iii. Detailed description of collection framework
1. Collection is an interface, which is a highly abstract Collection containing the basic operations and attributes of the Collection. Collection contains two branches: List and Set. (1) List is an ordered queue, each element has its index. The first element has an index value of 0. The List implementation classes are LinkedList, ArrayList, Vector, and Stack.
(2) A Set is a Set that does not allow duplicate elements. The implementation classes of Set are HastSet and TreeSet. A HashSet relies on a HashMap, and is actually implemented through a HashMap; TreeSet relies on TreeMap and is actually implemented through TreeMap.
2. Map is a mapping interface, that is, key-value pair. Each element in the Map contains a key and a value corresponding to the key. AbstractMap is an abstract class that implements most of the APIS in the Map interface. HashMap, TreeMap, WeakHashMap all inherit from AbstractMap. Although Hashtable inherits from Dictionary, it implements the Map interface.
3. Next, Iterator. It is a tool for iterating over collections, that is, we usually iterate over collections through iterators. We say that a Collection depends on Iterator because each of the Collection’s implementation classes implements an Iterator () function that returns an Iterator object. ListIterator exists specifically for traversing lists.
4. Enumeration, an abstract class introduced in JDK 1.0. Like Iterator, Iterator iterates over collections; But Enumeration has less functionality than Iterator. In the block diagram above, Enumeration can only be used with Hashtable, Vector, and Stack.
Finally, Arrays and Collections. These are two utility classes that operate on arrays and collections.
Collections and arrays
Fifth, hierarchical relationship
Introduction to several important interfaces and classes
Seven, traverse
ArrayList and LinkedList
9. Map collection
Ten, the main implementation of class differences summary………
Java Basics – Multithreading
First, the basic concept of multithreading
Common thread related methods
Inherit the Thread class
Implement Runnable interface
Java has two types of threads: user threads and daemon threads
The user thread is the foreground thread, and the daemon thread is the background thread
What is reentrant lock?
8. The difference between Lock and synchronized
9. Use of synchronized
The underlying implementation principle of Atomic package
The underlying principle of Lock
Twelve, the underlying reasons for multithreading insecurity and the difference between the two locking methods
All kinds of locks in Java multithreading
Locking in Java multithreading (supplement)
BlockingQueue
Java thread pool, Java thread pool progression, ThreadLocal in Java
Java Basics – Framework Basics: Annotations/reflection/pop frameworks
Optimize the 7 measures Hibernate encourages
Serialization and deserialization
The concept of pools in Java
Java reflection
5. IOC and AOP concepts and implementation principles of Spring
Implement simple IOC after Spring
Implement simple AOP modeled after Spring
Life flow of Spring Bean
Authoring AOP and IOC collaboration in Spring
Java Basics – Object-oriented: inheritance/polymorphism/encapsulation
Rewrite and overloading
Single inheritance and multiple inheritance
Third, polymorphism
4. Super and this
Java Basics – Design patterns
Slacker and hungrier singleton patterns
The observer model of design pattern
Factory mode of design mode
4. Agent mode of design mode
Java Basics – JVM/ class loading
Initialize the order of execution of code (including static and constructor blocks) and class and instance methods
Second, JVM memory structure
Components of JVM
Class loading mechanism
Class loaders
Relationships between Java class loaders
7. Objects in VMS
8. Allocate memory for the VM
Reference types in Java
How does the JVM determine whether to reclaim an object
Garbage collection algorithm
JVM runtime data area
JVM garbage collector
JVM garbage collection
Memory leaks and memory overflow in Java
Java base – I/O
I/O Basic Concepts
I/O model – blocking, non-blocking, multiplexing, asynchronous
BIO, NIO and AIO in JAVA
Network programming and networking
Source code, inverse code and complement in Java
B) Forward and redirect
Three, the composition of URL
Four, the basic communication – IP, DNS, MAC address
V. Understanding of IP addresses
Working principle of GFW (Great Firewall of China
The OSI seven-tier model and five-tier architecture
TCP three-way handshake and four-way wave
Nine, TCP protocol (reliable guarantee, TCP, UDP, congestion, ARQ)
HTTP and HTTPS
Http/1.0, Http/1.1, Http2
Details of Https encryption process
13, HTTP protocol supplement (POST, GET request method, idempotency)
Network attack (XSS, CSRF) details
Explanation of DDoS attacks
SQL injection attack details
The database
Comprehensive analysis of ResultSet
2. Basic concepts
Three, index,
Four, transaction
Storage engines
Sixth, database optimization
Database lock
Master/slave replication and read/write separation
The operating system
First, the thread process part
Memory and interrupts
Mutual exclusion and synchronization
4. Linux related commands
Linux IO mode and select, poll, epoll
The data structure
Linked list, array, character, tree
Heap, stack, queue
B tree, B+ tree, B* tree
Fourth, Java implementation of sorting algorithm, compare the time complexity
Red black tree
Stack of data structures
Search and backtracking algorithm -Java implementation
8. Determine whether a number is prime or not
The last
Personal study notes have been organized into PDF documents, mainly including Java foundation, data structure, JVM, multi-threading, Spring family bucket and other contents, including: MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, Spring Boot, Spring Cloud, RabbitMQ, Kafka, Linux, etc.
Wish you all a happy New Year and a smooth interview!!