1. What are the basic data types in JAVA, and how many bytes each take up?

Can the String class be inherited? Why

Can’t. In Java, any class defined as final, or modified by final, cannot be inherited.

3, Stringbuffer, StringBuilder

4. What’s the difference between ArrayList and LinkedList?

ArrayList is a data structure based on dynamic arrays, while LinkedList is a data structure based on linked lists. (LinkedList is a two-way LinkedList, with next and previous) 2. ArrayList feels superior to LinkedList for random access to GET and set because LinkedList moves the pointer. 3. For add and remove operations, LinedList has an advantage because ArrayList moves data.

Depth difference: 1. For both ArrayList and LinkedList, the cost of adding an element to the end of the list is fixed. With an ArrayList, it is essentially adding an entry to the internal array that points to the added element, occasionally causing the array to be reallocated. For LinkedList, this overhead is uniform, assigning an internal Entry object.

2. Inserting or deleting an element in the middle of an ArrayList means that the rest of the list is moved; The overhead of inserting or deleting an element in the middle of a LinkedList is fixed.

3. LinkedList does not support efficient random element access.

4. The space waste of ArrayList is mainly reflected in reserving a certain amount of space at the end of list, while the space cost of LinkedList is reflected in that each element of it needs to consume a certain amount of space

Talk about the order in which classes are instantiated.

Problems: such as superclass static data, constructors, fields, subclass static data, constructors, segments, when new, their execution order.

Answer: The steps taken when the class loader is instantiated (load -> connect -> initialize). Superclass static variable, superclass static code block, subclass static variable, subclass static code block, superclass non-static variable (superclass instance member variable), superclass constructor, subclass non-static variable (subclass instance member variable), subclass constructor.

6. What are the differences between Map classes used?

Question: Are Hashmaps thread safe, what are the maps used concurrently, what are their internal principles, such as storage, Hashcode, capacity expansion, default capacity, etc. Answer: unsafe, ConcurrentHashMap is used concurrently.

Why did JAVA8’s ConcurrentHashMap abandon segment locking?

Reasons: According to the JDK source code and official documentation, they believe that the reasons for abandoning the fragment lock are as follows: 1. Adding multiple fragment locks wastes memory space. 2. In the production environment, the probability of a map competing for the same lock is very small when it is put into the production environment. 3. To improve the efficiency of GC

Since abandoned the piecewise lock, then must be by the new thread safety solution, we look at the source code is how to solve the thread safety? CAS

After first finding the corresponding linked list through hash, check whether it is the first object. If it is, insert it directly using cas principle without locking. Then, if it is not the first object in the linked list, lock it directly with the first object in the linked list. Although not as efficient as ReentrantLock, it saves space by using the first object as the lock until the map is recalculated, for example by expanding or manipulating the first object.

ConcurrentHashMap(JDK1.8) why synchronized instead of ReentranLock?

It can be described from the following aspects: Granularity of locks First of all, the granularity of locks does not become thicker, or even finer. Each expansion doubles the concurrency of ConcurrentHashMap. In JDK1.7, ConcurrentHashMap can quickly find the elements to be searched by using the Segment -> HashEntry method. In 1.8, the performance gap of PUT and GET is covered by linked list and red-black tree. In the expansion JDK1.8, when ConcurrentHashmap is used for expansion, other threads can determine whether to expand the linked list (red-black tree) by detecting the nodes in the array. This reduces the granularity of expansion and improves the efficiency of expansion.

Why synchronized and not reentrant

  1. Reducing memory overhead Assuming that reentrant locks are used for synchronization support, each node needs to inherit AQS for synchronization support. However, not every node needs to be synchronized. Only the head node of the linked list (the root node of the red-black tree) needs to be synchronized, which is a huge waste of memory.
  2. Getting JVM support for reentrant locks is, after all, at the API level, leaving little room for further performance optimization. Synchronized is directly supported by the JVM and can be optimized at run time: lock coarsening, lock elimination, lock spin, and so on. This allows synchronized to gain performance gains with JDK versions without changing the code.
9. Are there any sequential Map implementation classes, and if so, how do they ensure order?

Neither Hashmap nor Hashtable is ordered. Both TreeMap and LinkedHashmap are ordered. (TreeMap defaults to key ascending and LinkedHashmap defaults to data insertion order.) TreeMap implements order based on the Comparator’s Comparator. LinkedHashmap is based on linked lists for data insertion order.

www.iteye.com/blog/uule-1…

10, the difference between abstract classes and interfaces, classes can inherit multiple classes, interfaces can inherit multiple interfaces, classes can implement multiple interfaces?

Abstract class variables must point to the subclass object that implements all of the abstract methods, and interface variables must point to the class object that implements all of the interface methods. 2. Abstract classes are inherited by subclasses and interfaces are implemented by classes. 3, interface can only do method declaration, abstract class can do method declaration, also can do method implementation 4, interface defined variables can only be public static constants, abstract class variables are ordinary variables. All methods in an abstract class must be implemented by the subclass. If the subclass cannot implement all of the methods in its parent class, the subclass must be an abstract class. Similarly, when an interface is implemented, if not all interface methods are implemented, then the class must be abstract. Abstract methods can only be declared, not implemented. abstract void abc(); Cannot be written as abstract void ABC (){}. If a class has abstract methods, the class must be abstract. 9. Abstract methods are implemented, so they cannot be static or private. Interfaces can inherit interfaces, and can inherit more than one interface, but a class can only inherit from a single root.

Classes cannot inherit from more than one class interface Can inherit from more than one interface Classes can implement more than one interface

What is the difference between inheritance and aggregation?

Inheritance refers to the ability of a class to inherit the functions of another class and add its own new functions. Inheritance is the most common relationship between classes or interfaces. In Java, such relationships are explicitly identified by the extends keyword.

The aggregation

Aggregation reflects the relationship between the whole and part, and ownership. At this time, the whole and part can be separated, and they can have their own life cycle. For example, the relationship between computer and CPU, company and employee, etc.

12. What are IO models? Talk about your understanding of NIO, what is the difference between BIO and AIO, and reactor model.

IO differences:

What is a reactor?

  1. event-driven
  2. Can process one or more input sources
  3. The Service Handle synchronously multiplexes input events to the corresponding Request Handler(one or more) for processing

What are the three ways to create class instances by reflection?
Class class1 = p1.getClass(); Class class1 = p1.getClass(); Class: you need to enter an explicit Class, each of which has a static Class attribute.) Class class3 = person.class; // Create a Class objectforName(): just pass it as a string) // through one of the Class classesforStatic methods return a Class object. ClassName must be the full path Name; // Class.forname () has an exception: ClassNotFoundException Class class4 = class.forname ()"cn.xbmchina.Person");
        
Copy the code

Blog.csdn.net/LianXu3344/…

In reflection, class. forName is different from ClassLoader.

Class.forname (className) method, the method of internal actual call is Class class.forname (className, true, this); The second Boolean argument indicates whether the Class needs to be initialized. Class.forname (className) does by default. Once initialized, the static block of the target object is triggered, and the static parameter is initialized again. Classloader.loadclass (className), the actual internal call is classLoader.loadClass (className,false); Boolean indicates whether the target object is linked. False indicates whether the target object is not linked. Boolean indicates whether the target object is linked

www.cnblogs.com/zabulon/p/5…

15, describe several implementation methods of dynamic proxy, respectively, the corresponding advantages and disadvantages.

Principle difference:

Java dynamic proxies use reflection to generate an anonymous class that implements the proxy interface and InvokeHandler is invoked to handle it before invoking the specific method.

The cglib dynamic proxy uses the ASM open source package to load the class file of the proxy object class and modify its bytecode generation subclass to deal with it.

If the target object implements the interface, CGLIB can be used to implement AOP by default

3. If the target object does not implement an interface, the CGLIB library must be used, and Spring will automatically convert between JDK dynamic proxies and CGLIB

How do I enforce AOP with CGLIB? <aop:aspectj-autoproxy proxy-target-class=”true”/>

What is the difference between JDK dynamic proxy and CGLIB bytecode generation? (1) JDK dynamic proxies can only generate proxies for classes that implement interfaces, not for classes. (2) CGLIB implements proxies for classes, mainly by generating a subclass of the specified class that overrides its methods

Blog.csdn.net/qq_23000805…

16. Use of final.

Classes modified by a final modifier cannot be inherited. Methods modified by a final modifier cannot be overridden. Variables modified by a final modifier cannot be changed. 4. The JVM will try to find inlining for methods that are modified by final, which is important to improve Java efficiency. 5. Constants modified by final are stored in the constant pool of the calling class at compile time. For details, see the last section of the classloading mechanism and the Java memory area

www.cnblogs.com/swisszhang/…

17, write three singleton pattern implementation.

1 the hungry

public class EagerSingleton {
static {
     System.out.println("EagerSingleton loaded."); } // Private constructor, restrict direct construction, only call getInstance() to get the singleton privateEagerSingleton(){} private static final EagerSingleton eagerSingleton=new EagerSingleton(); Public static EagerSingleton public static EagerSingleton public static EagerSingletongetInstance(){// Provide an external public API to get singletonsreturneagerSingleton; }}Copy the code

Summary: A hungry singleton instantiates a static object at the same time the class is created. Regardless of whether the singleton is used later, it takes up some memory, but is also faster on the first call because its resources are initialized.

2 LanHanShi

public class LazySingleton {
static {
    System.out.println("LazySingleton loaded");
}

private LazySingletonPrivate static LazySingleton =null; private static LazySingleton =null; Public static LazySingleton public static LazySingleton public static LazySingletongetInstance(){// Provide an external public API to get singletonsifSynchronized (lazySingleton==null){synchronized (lazySingleton==null){synchronized (lazySingleton==null){synchronized (lazySingleton==null){ At the same time, the performance loss of synchronization is avoidedif(lazySingleton==null){ lazySingleton = new LazySingleton(); }}}returnlazySingleton; }}Copy the code

Summary: There is a performance cost of synchronous locking

Static inner class implementation

public class IoDHSingleton {
static {
System.out.println("IoDHSingleton loaded");
}

private IoDHSingletonPublic static IoDHSingleton (){// privatize the constructor, restrict the direct constructor, only call getInstance() to get the singletongetInstance() {/ / provide foreign public API for singleton / / when getInstance method is invoked for the first time, read it first HolderClass. IoDHSingleton, internal HolderClass class get initialized; // When the class is loaded and initialized, it initializes its static domain, thus creating the ioDHSingleton instance. Since it is a static domain, it is initialized only once when the virtual machine loads the class, and the virtual machine guarantees its thread-safety.return HolderClass.ioDHSingleton; 
}

  private static class HolderClass{
    static {
       System.out.println("HolderClass loaded"); } private static IoDHSingleton ioDHSingleton = new IoDHSingleton(); } // Prevent deserialization of multiple objects private Object vulnerabilityreadResolve() throws ObjectStreamException {    
       returnHolderClass.ioDHSingleton; }}Copy the code

The advantage of this pattern is that the getInstance method is not synchronized and only performs access to a domain, so delayed initialization does not add any access costs.

Consider reflection: Since singletons are initialized when singletonholder.instance is called, it is not possible to obtain properties of inner classes from outer classes through reflection. So this is a pretty good way to avoid reflective intrusion. Consider multithreading: Due to the nature of static inner classes, they are only loaded the first time they are referenced, so they are thread-safe. Summary: Advantages: Memory optimization in lazy mode (initialized only when used) and security in Hungry mode (not invaded by reflection). Disadvantages: It takes two classes to do this. Although no static inner Class object is created, its Class object is created anyway, and it is an object belonging to the permanent band.

www.cnblogs.com/ngy0217/p/9…

How do I automatically complete all hashCode and equals implementations for subclasses in a parent class? What are the pros and cons of this.

www.iteye.com/blog/java-m…

19. Discuss the role of access modifiers public, private, protected, and default in application design.

Access modifier, mainly marking the scope of the modifier block, convenient isolation protection.

Public: The widest access-restricted modifier in the Java language, commonly called “public.” The classes, properties, and methods it modifies can be accessed not only across classes, but also across packages.

Private: The narrowest modifier in the Java language that restricts access, generally referred to as “private.” Classes, attributes, and methods that are modified by them can only be accessed by objects of that class, not subclasses, and not across packages.

Protect: An access modifier between public and private. Classes, attributes, and methods modified by them can only be accessed by methods and subclasses of the class itself, even if the subclasses are accessible in different packages.

Default: indicates that no access modifier is added, which is usually called the default access mode. In this mode, access is allowed only in the same package.

20. Difference between deep copy and shallow copy.

Shallow Copy:

(1) For member variables whose data type is a basic data type, the shallow copy will directly pass the value, that is, copy the value of the property to the new object. Since there are two different copies of data, changing the value of this member variable in one object does not affect the data copied from the other object. For a member variable whose data type is a reference to a data type, such as an array, an object of a class, etc., the shallow copy will be passed by reference, that is, only the reference value (memory address) of the member variable will be copied to the new object. Because the member variable of both objects actually refers to the same instance. In this case, modifying the member variable in one object affects the value of the member variable in the other object.

Deep copy:

First, the concept of an object graph is introduced. Imagine that a class has an object with an object in its member variable that points to another object, which points to another object, until a certain instance. This forms the object graph. Then, for deep copy, not only do you copy the values of all the member variables of the object’s base data type, but you also need to allocate storage space for all the member variables that reference the data type, and copy the objects referenced by each member variable of the reference data type until the objects are reachable. In other words, to make a deep copy of an object, you must copy the entire object graph!

In short, deep copy creates memory for all objects in the object graph that reference a member variable of a data type; The shallow copy just passes the address pointing, and the new object does not create memory for the reference data type.

www.cnblogs.com/shakinghead…

21, Array and linked list data structure description, their time complexity.

1, from the perspective of logical structure: array must define a fixed length (the number of elements), can not adapt to the dynamic increase and decrease of data. As the data increases, the number of elements may exceed the original definition; When data is reduced, memory is wasted. Linked list can dynamically allocate storage, adapt to the situation of dynamic increase and decrease of data, and can easily insert and delete data items. 2. Array elements are in stack area, linked list elements are in heap area; 3. From a memory storage perspective: (static) arrays allocate space from the stack, which is fast and convenient for programmers, but has little freedom. Linked lists allocate space from the heap, which has a lot of freedom but can be difficult to manage. The time complexity of array location is O(1), and the time complexity of linked list location element is O(n). The time complexity for inserting or deleting elements in an array is O(n), and the time complexity for linked lists is O(1).

Error and exception, CheckedException, RuntimeException.

23. If I create a java.lang.String class in my own code, can that class be loaded by the class loader? Why.

Blog.csdn.net/u013206465/…

24, Describe your understanding of the hashCode and equals methods in java.lang.Object. What are the scenarios in which these two methods need to be reimplemented?

For equals() and hashcode(), compare the general rule: ① Two obj, if equals(), hashcode() must be equal; ② two obj, if hashcode() is equal, equals() must not be equal

In jdk1.5, generics were introduced to solve what problems generics exist to solve.

Object-oriented transformations occur only in parent-child classes that have inherited relationships (interfaces are a type of inheritance) : the core purpose is to unify parameters, and no casts are required at all. Downcast: to operate on special functions defined by subclasses, casting is required, but there is a problem: downcast is actually a very unsafe operation, because the program will not report errors at compile time, but will report errors at run time, this is the fabled – error.

However, with the addition of generics after JDK1.5, these downward transition issues were nipped in the bud. The core of generics is that a class can be defined with a tag that represents the type of an attribute or method or parameter in the class. When the tag is used, the type is dynamically set.

How does a HashSet in Java work internally?

The inside of a HashSet is implemented using a HashMap. Since maps require keys and values, all keys in a HashSet have a default value. Similar to a HashMap, a HashSet does not allow duplicate keys. Only one NULL key is allowed, meaning that only one NULL object can be stored in a HashSet.

Blog.csdn.net/qq_32575047…

What is serialization, how serialization, why serialization, deserialization will encounter what problems, how to solve.

What is serialization? Serialization: The process of converting an object into a sequence of bytes is called object serialization. Deserialization: The process of restoring a sequence of bytes to an object is called deserialization of an object

When is serialization needed? When you want to save the state of an object in memory to a file or database; When you want to use a socket to send objects over the network; When you want to transfer objects over RMI;

How is serialization implemented? Implement the Serializable interface

Note: transient attributes are static attributes that will not be serialized; they are not serialized. When implementing the Serializable interface, be sure to assign a value to the serialVersionUID

A description of serialVersionUID: The serialization runtime is associated with each serializable class using a version number called serialVersionUID, which is used during deserialization to verify that the sender and receiver of the serialized object loaded a serialization-compatible class for the object. If the serialVersionUID of the object’s class loaded by the receiver is different from the version number of the corresponding sender’s class, deserialization will result in an InvalidClassException. Serializable classes can explicitly declare their own serialVersionUID by declaring a field named “serialVersionUID” (which must be a static, final, long field)

Blog.csdn.net/riemann_/ar…

New features in java8.

www.cnblogs.com/frankdeng/p…