1. Describe the automatic packing and unpacking of objects 2

Autoboxing and unboxing for basic data types are features available starting with J2SE 5.0. Automatic boxing is an automatic conversion made by the Java compiler between Java native types and the corresponding object wrapper types.

Integer I = 1; Integer I = integer.valueof (1); Automatic unpacking: Integer I = 1; int a = i; Int a = i.ntValue ();Copy the code

Difference between int and integer:

Int is a basic type that stores values directly. When initialized, the variable of int class starts with 0.integerIs an object with a reference to it, and the Integer variable is initialized to NULL.Copy the code

2. Data types supported by the Switch

Includes byte, short, char, int, and enum, as well as wrapper types Character, byte, short, and Integer. String support has been added since java7. Support for String: use stringshashValue as the value of the expression, and since there is still the possibility of conflict in the case of the same hash value, all incaseBlock statements still need to check equality through equals.Copy the code

Equals == hashCode:

== : Compares equality of reference addresses or equality of primitive data types/enumerated types Equal: Equality of value cases of objectshashCode: Returns the storage address relation of the object: comparison of two objects: euqals returnstrueWhen,hashCode is the same.hashIf Code is equal, equals does not necessarily return equal. Instanceof: checks whether object type 5 is equal. The parent and the child have one-way judgment. == = equals (); instanceof (); attribute matching (); reflexivity (); symmetry (); transitivity (); consistency (); overwrite hashCode ()Copy the code

1 + 2+ 3+ 4+ 5 + (16*1) = 31 but 12345 does not equals 54321

Create object;

There are four main object creation methods: 1, new 2, reflection (both of which call the constructor) 3,cloneAmong them: clone: Cloneable, Serializable (serialization, deserialization implementation) to realize the object clone reflection: the performance of this mode is mainly: 1, runtime to obtain fields and methods and modify (including constants) 2, create object principle: Advantages and disadvantages: Increased programming flexibility; High performance consumptionCopy the code

5, briefly describe the realization principle of polymorphism,Java polymorphism? Understanding dynamic binding? :

1, object-oriented three features: encapsulation, inheritance, polymorphism. 2. Definition of polymorphism: The same message can behave in many different ways depending on the function call. 3. Polymorphism is used to decouple types from each other. Four, three necessary conditions: first, to have inheritance; Two, to have rewrite; Parent class references refer to subclass objects. Overloading: in the same class, the function of the same name has different parameter forms, based on the actual type of the object to choose the method to call, to achieve the purpose of dynamic binding. Override: redefines the implementation of a method with the same name and argument in a parent or subclass. Differences: compile-time polymorphism, run-time polymorphism (except for static methods, where polymorphism is for instance methods)Copy the code

Associating a method call with a method body is called binding, and in JAVA there are early binding and late binding (dynamic binding or runtime binding). Early binding: Binding before program execution (implemented by the compiler and linker) is called pre-binding, because the direct address of the called method at compile time is already stored in the constant pool of the method’s class, and is called directly at program execution.

Late binding: The idea is to bind objects according to their type at runtime. To bind later, you must have some mechanism for determining the type of the object at runtime and finding the corresponding method. In short, you must place some kind of “type letter” in the object. In JAVA, all methods except static and final (private) methods are late bound.

Java technology —- the implementation principle of polymorphism

6. Outline the differences between abstract classes and interfaces:

An interface is an abstraction (implementation) of an action, and an abstract class is an abstraction of the source. 2. An interface is a variant of an abstract class in which all methods are abstract. An abstract class is a class that declares the existence of a method without implementing it. Abstract classes are inherited by subclasses and interfaces are implemented by classes. 4. Variables defined in interfaces can only be public static constants. Variables in abstract classes 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. 7. If a class has abstract methods, it must be an abstract class. Abstract classes, unlike ordinary classes, cannot be instantiated directly, can have constructors, and subclasses may not implement their abstract methods. Interface: modifiers are public, variables are final, there is no real method, can achieve multiple inheritance.Copy the code

The meaning of abstract classes:

Abstract method: the method modified by abstract is abstract method. Abstract method only has the definition of method, but does not have the implementation of method. Abstract Classes: A class that contains abstract methods should be declared abstract using the abstract keyword. Abstract classes cannot be instantiated. A class can be defined as an abstract class even if there are no abstract methods in it. Provide common methods for subclasses. b. Encapsulate repeating content (member variables and methods) in subclasses. c. There are abstract methods defined, subclasses have different implementations,Copy the code

7. Describe the differences between public, protected, private and default

Also called scope modifier public Scope: current class, same package, subclass, other package; Protected Scope: current class, same package, subclass; Default scope: current class, same package; Private Scope: current class;Copy the code

8. Briefly describe how to create a thread:

1. Directly through new Thread; 2. Implement runnable interface; 3, through the interface callable (callable can get the return value and throw exceptions); 4. Generate threads by thread pool;Copy the code

9, sleep, wait, yield, notify, notifyall:

The difference between sleep and yield is that sleep gives the thread no priority.thenBlock yield: execute to the thread with the highest priority and then enter the ready statewaitThe difference between sleep and sleep:waitNotifyall: after a thread is interrupted by interruption or interrupted, a thread notifyall is used to unlock an object. Wake up all waiting threads to compete for the lockwait/notify/ notifyAll: both of them need to be called in the synchronization block and release the object lock.wait: Release control immediately However blocked (Notify required) Notify: Release control again after the executionCopy the code

10, synchronized, Lock differences:

Synchronized: the object can control the time and information about the acquisition of the Lock manually release the Lock, make the thread respond to the interrupt, know whether the Lock is obtained or not When multi-threading competition is fierce, Lock is better Context switch: CPU control is switched from a running thread to another thread in the ready stateCopy the code

11. Exception Handling:

Error, Exception: parent class: Throwable: contains exceptionslogError: a system-level Error, such as OOM Exception: a program design Error that needs to be caught and handled by the program. Throw: Throws an Exception ina method. Throws: declares an Exception. The try ofreturnThe return value is recorded after finally is executed. The return value remains the same as in finallyreturnThen the value changes finally: releases external resourcesCopy the code

12, Briefly describe the JVM memory model: 2

JVM memory model can be divided into thread shared area and thread private area, thread shared area: Java heap (objects and arrays, GC), method area (class information, constants, static variables, etc., permanent generation); Thread private area: program counter (indicating code execution, no OOM), Java virtual machine stack (Java method call), Native method stack; Whereas each thread has its own stack memory, the heap is shared and threads cache objects for use on the stack, volatile can require threads to read from memoryCopy the code

13. Briefly describe the GC mechanism: 2

Java memory reclamation algorithm can be divided into: generation reclamation: young generation (create), old generation (stay long), permanent generation mark-copy algorithm: The area is divided into two pieces, one piece is recycled, and the other piece is recycled alternately. When the free area is full, it is copied to the old age area by the mark-clean, mark-tidy algorithmCopy the code

14, algorithm

Sorting (must be handwritten)

Public static void BubbleSort(int [] arr){int temp; // Temporary variablesfor(int i=0; i<arr.length-1; I++){// indicates the number of trips, total arr.length-1 times.for(int j=arr.length-1; j>i; j--){
                
                if(arr[j] < arr[j-1]){ temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; }}}}Copy the code

Summary of sorting algorithm

Find ()

Copy the code

Basic data types in Java? How many places are there in each? How many bytes? Value range? Is String a primitive type or a reference type?

Basic data types (8): 2.Short 16 2-32768 ~ 32678 3. Long 648 - 9223372036854775808 ~ + 9223372036854775807 4. Float 32-3402234 - E + 38 ~ + 3402234 7 E + 5. 38 double 8 64 Char 16 2 '\u0000' ~ '\uFFFF' 7. Boolean 1 + + 1.79769313486231576 + 1.79769313486231576true/falseByte 8 1-128 to 127 String indicates the reference type.Copy the code

16. When is Java value passing and when is Java reference passing?

When passing a value, copy the value of the argument to the parameter. When passing a reference, copy the address value of the argument to the parameter. Whether passed by value or reference, a parameter gets only a copy of the argument, not the argument itself.Copy the code

Is Java value Passing? Passing by reference?

17, String related. String Constant pool, StringBuffer, StringBuilder. String immutable understanding. String intern method different versions of the implementation principle of the difference.

String constant pooling: The JVM implements some optimizations when instantiating String constants to improve performance and reduce memory overhead. To reduce the number of strings created in the JVM, the string class maintains a string pool that is first examined by the JVM whenever code creates string constants. If the string already exists in the pool, the instance reference in the pool is returned. If the string is not in the pool, a string is instantiated and placed in the pool. Java can do this optimization because strings are immutable and can be shared without worrying about data collisions.

Pay attention to the interview questions in the article: (Looks like being abused!!) Constant pool summary of String

StringBuffer, StringBuilder, CharSequence StringBuilder > StingBuffer > String StringBuffer String variable (thread-safe) StringBuilder String variable (non-thread-safe) The CharSequence interface.

A ++ and ++a difference, if used alone without any difference, if there is a difference in the operation, a++ is the first operation in the assignment, and ++a is the first assignment in the operation!!

String is immutable.

For example: String STR ="aa";  str = "aa"+"bb"; The value of STR is zero"aabb", but"aabb"Not at the beginning of the string"aa"Directly connected to the back"bb"Instead, it is regenerated as a string"aabb"The string"aa"Once initialized, its value cannot be changed. StringBuffer strb = StringBuffer("aa");  strb.append("bb"); The value of STRB is also zero"aabb", but"aabb"Is the string directly at the beginning"aa"The concatenated "bb" does not generate a new string. The bottom layer of a String is actually a char[] array: private final char value[]; Final objects are variable in value, but not in reference. The underlying StringBuffer object is also a char[] array: char[] value;Copy the code

Why is String immutable and StringBuffer mutable?

JAVA Collections Framework

  • Collection: Stores a single data or object.

    • | – List: a List:
      • | – LinkedList: List based on chain table
      • | – ArrayList: the List based on array
      • | – SubList: a List view
      • | – Vector: a thread safe List
        • | – Stack: Stack
    • * * | – Queue, Queue, usually as a data storage structure, not as a container operation. ** Collections are used less in the framework, mainly in the blocking queue (message queue) implemented in concurrent packet (java.util.concurrent).
      • | – ArrayDeque: based on array implementation tail cut in line column (the head and tail pointer contains a head, tail).
      • | – PriorityQueue: since the scheduling priority queue based on array (binary tree based on array to realize the storage pile row).
    • | – Set: one is not allowed to repeat the data collection
      • | – HashSet: based on the Hash array + + list to achieve the Set.
        • | – LinkedHashSet: a LinkedHashMap based implementation of the Set.
      • | – TreeSet: a TreeMap based implementation of the Set.
      • | – enumsets:
        • |-JumboEnumSet
        • |-RegularEnumSet
  • Map: Stores a set of K-V key-value pairs.

    • | – HashMap: based on the Hash array + + list implementation of the Map.
      • | – LinkedHashMap: based on the HashMap implementation of two-way linked list. LruCache implementation base
    • | – HashTable: based on the Hash array + + list implementation thread-safe (sync) Map.
    • | – TreeMap: based on the red-black tree orderly implementation of the Map.
    • | – WeakHashMap: K HashMap for weak references, use, if K is not reference is automatically collection

The only two thread-safe collections in the collection framework

Vector(Stack is a safe subclass of Vector) HashtableCopy the code

ArrayList,LinkedList similarities and Differences:

  • Similarities:
    • List is an interface that encapsulates arrays. All implementation classes can convert arrays and get indexes. ArrayList and LinkedList are just different implementations
  • Difference:
    • ArrayList encapsulates arrays, making it easier to operate on arrays. It is faster to query and slower to add and delete arrays. LinkedList is an implementation of a LinkedList that is fast to add and delete but slow to query

HashMap, associations and differences in HashTable:

The main difference between HashMap and HashTable is that HashTable is thread-safe. Both HashMap k-v and HashTable k-v can be null.

ArrayList vs. Vector

  • Similarities: Both classes implement the List interface (the List interface inherits the Collection interface). They are both ordered collections, that is, the positions of the elements stored in the two collections are ordered, which is equivalent to a dynamic array.
  • Difference:
    • Vector is thread-safe, that is, its methods are thread-synchronized, whereas ArrayList is threadless, its methods are thread-out
    • ArrayList and Vector both have an initial capacity. When the number of elements stored in them exceeds the capacity, the storage space of ArrayList and Vector needs to be increased. Vector is doubled and ArrayList is 0.5 times larger.

Added: Bottom data structure? Hash table conflict handling method, what is a hash table data structure? What approach does HashMap take to handle conflicts?

A HashMap uses a so-called "Hash algorithm" to determine where each element is stored. When the program executes the map.put(String,Obect) method, the system calls String'shashThe Code() method gets ithashCode value - every Java object has ithashThe Code() method is available through that methodhashCode values. To get this objecthashAfter the Code value, the system will use thehashCode value to determine where to store the element. HashMap takes the form of a linked list, which is a one-way list. The linked list method is going to be the samehashValues of objects organized into a linked list are placedhashValue Indicates the slot number. When creating a HashMap, there is a default load factor, which defaults to 0.75. Increasing the load factor reduces the memory footprint of the Hash table (that is, the Entry array) but increases the time spent querying the data. Queries are the most frequent operations (both the Get () and put() methods of HashMap use queries); Reducing the load factor improves the performance of data queries, but increases the memory used by Hash tables. http://blog.csdn.net/u011202334/article/details/51498893Copy the code

Collection Framework Java container framework

19. Java container-related helper classes Arrays and Collections .

  • Array: Array
    • Array: Array class that provides methods for dynamically creating and accessing Java arrays.
    • Arrays: utility class that contains methods for manipulating Arrays directly, such as sorting (sort()) and searching (binarySearch()).
  • The difference between Collections and Collections:
    • Collection: Collection interface (a top-level interface of a Collection class)
    • Collections: A utility/helper class of the collection class that provides a set of static methods for sorting, searching, and thread-safe operations on elements in the collection.

Java final, Finalize () and finally

  • Final: keyword can be used before a class, method, or variable to indicate that the class, method, or variable modified by the keyword is immutable
    • The final keyword is used before basic data types: this indicates that the variable modified by the keyword is a constant and its value cannot be modified after definition.
    • The final keyword is used before a method declaration: this means that the method is the final method and can only be called, not overridden, but can be overridden.
    • The final keyword is used before the class name: the class is called final and cannot be inherited by other classes.
  • Finalize () : Finalize method comes from java.lang.object and is used to recycle resources.
    • You can add finalize methods to any class. The Finalize method will be called before the garbage collector cleans up the object. In practice, do not rely on using this method to reclaim any scarce resources, because it is difficult to know when this method is called.
  • Finally: When code throws an exception, it terminates the processing of the rest of the code in the method and exits execution of the method (code block). Finally try catch order problem

How to start a thread in Java. What does a thread pool do? What thread pools are commonly used? What are the pros and cons?

How to start a thread:

1, Thread class:

/ / 1) : define A class A inheritance in Java. Lang. The Thread class. The class MusicThread extends Thread {/ / 2) : covered in the class A run method in the Thread class. The public voidrun() {//3): Write the operation to be performed in the run methodfor(int i = 0; i < 50; i ++){  
            System.out.println("Play the music"+i);  
        }  
    }  
}  
  
public class ExtendsThreadDemo {  
    public static void main(String[] args) {  
          
        for(int j = 0; j < 50; j ++){  
            System.out.println("Run the game"+j);  
            if(j == 10){//4): In the main method (thread), create a thread object and start the thread. MusicThread music = new MusicThread(); music.start(); }}}}Copy the code

Implement Runnable interface:

Runnable{//2): implements the Runnable method on the java.lang.Runnable interface. public voidrun() {//3): Write the operation to be performed in the run methodfor(int i = 0; i < 50; i ++){  
            System.out.println("Play the music"+i);  
        }  
          
    }  
}  
  
public class ImplementsRunnableDemo {  
    public static void main(String[] args) {  
        for(int j = 0; j < 50; j ++){  
            System.out.println("Run the game"+j);  
            if(j == 10){//4): In the main method (thread), create a thread object, and start the thread MusicImplements mi = new MusicImplements(); Thread t = new Thread(mi); t.start(); }}}}Copy the code

3, use directly in the function body (special second type) :

void java_thread()  
{  
  
     Thread t = new Thread(new Runnable(){  
            public void runMsoundpoolmap. put(index, msoundPool.load (filePath, index)); getThis().LoadMediaComplete(); }}); t.start(); }Copy the code

P: What is the difference between inheritance and implementation? (Encountered)

  • Inheritance mode:
    • By design, Java classes are single-inheritable. If Thread is inherited, the class cannot have any other direct parent.
    • Operationally, inheritance is easier and getting the thread name is easier.
    • From the analysis of multi-thread sharing the same resource, inheritance mode can not do it.
  • Implementation method:
    • From the design analysis, Java classes can implement multiple interfaces, this class can also inherit other classes, and can also implement other interfaces, design is more reasonable.
    • Thread.currentthread () is used to retrieve references to the currentThread.
    • From the multi-thread sharing the same resource analysis, the implementation can be done (whether to share the same resource).

Thread pool composition

  • ThreadPool manager: used to create and manage thread pools, including creating thread pools, destroying thread pools, adding new tasks;
  • PoolWorker: a thread in a thread pool that is in a waiting state when no task is available and can execute tasks in a loop.
  • Task interface: The interface that each Task must implement for the worker thread to schedule the execution of the Task. It mainly defines the entry of the Task, the finishing work after the Task is executed, and the execution status of the Task.
  • TaskQueue: Stores unprocessed tasks. Provide a buffer mechanism.

What thread pools are commonly used? What are the pros and cons?

Thread life cycle:

Comparison of several methods:

  • Thread.sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis), thread. sleep(long millis) ** function: The best way to give other threads a chance to execute.

  • Obj. Wait (), obj method, the current thread calls the object’s wait() method, and the current thread releases the object lock and enters the wait queue. Wake up by notify()/notifyAll() or wait(long timeout)timeout time to automatically wake up.

  • Thread.yield(), which must be invoked by the current Thread. The current Thread gives up the CPU time slice and changes from the running state to the runnable state, allowing the OS to select threads again. The ** function allows threads of the same priority to be executed in turn, but does not guarantee that they will be executed in turn. In practice, there is no guarantee that yield() will yield because the yielding thread may be selected again by the thread scheduler. Thread.yield() does not block.

  • The join method of thread 1 is called in the current thread. The current thread blocks but does not release the object lock until thread 1 finishes executing or millis time expires and the current thread is ready to run.

  • Obj.notify () wakes up a single thread waiting on this object’s monitor, and the selection is arbitrary. NotifyAll () wakes up all threads waiting on the monitor of this object.

22. The role of the Volidate keyword?

  • The volatile keyword not only prevents instruction reordering
  • Ensure that the value of the variable accessed by the thread is the latest value in main memory.

What is the singleton pattern? The rationale for Volidate and instruction reordering

23. Use of Java Clone.

Person p = new Person(23, "zhang"); Person p1 = (Person) p.clone(); System.out.println(p); System.out.println(p1); Print results: / / com. Pansoft. Zhangjg. Testclone. Person @ 2 f9ee1ac / / com. Pansoft. Zhangjg. Testclone. F1fba0 Person @ 67Copy the code

Clone method in Java

24. Java reflection

Reflection mechanism: enables a program to retrieve information about itself at runtime. In Java, given the name of a class, all information about the class can be obtained through reflection.Copy the code

Function provided: at run time can determine the class of any object at run time to construct any object of any class at run time to determine the member variables and methods of any class at run time to call the methods of any object at run time to create a new class object at run time

Pros and cons of reflection:

  • Advantages: The advantage of reflection mechanism is that it can achieve dynamic object creation and compilation, reflecting a great deal of flexibility
  • Disadvantages: Performance is affected. Using reflection is basically an interpretation operation where we can tell the JVM what we want to do and it meets our requirements. This type of operation is always slower than just performing the same operation directly.

Java static proxy and dynamic proxy

Java static and dynamic proxies

Person = new Person(); Take as an example

Loading a class means reading the binary data from the class’s.class file into memory, placing it in the method area of the runtime data area, and then creating a java.lang. class object of that class in the heap to encapsulate the objects of the class in the method area.

The entire life cycle of a class begins when it is loaded into memory and ends when it is unloaded from memory: load, validate, prepare, parse, initialize, use, unload

The three stages: verification, preparation and analysis are collectively called “connection”.

Class loading process:

Including: load, verification, preparation, analysis and initialization of five stages.

Ali, Baidu have asked themselves to do!

27. What is an inner class? The role of inner classes

An Inner Class is a Class defined inside another Class. A corresponding class that contains an inner class is called an outer class. 2. Functions: a. Inner class provides better encapsulation. It can hide the inner class inside the outer class and does not allow other classes in the same package to access class B. Methods of the inner class have direct access to all data of the outer class, including the private data C. An inner class can do the same thing with an outer class, but sometimes it's more convenient to use an inner classCopy the code

The difference between extends and super:

<? Extends T> defines an upper bound for parameter types: The parameter type must be T or a subtype of T <? Super T> qualifies the lower bound of the parameter type: the parameter type must be T or a supertype of TCopy the code

29. The difference between processes and threads

1, a program has at least one process, and a process has at least one thread. 2, the process has an independent memory unit in the execution process, and multiple threads share the memory, thus greatly improving the running efficiency of the program. 3, each independent thread has a program run entry, sequential execution sequence and program exit. But threads cannot execute independently and must depend on the applicationCopy the code

30, Serializable and Parcelable differences:

  • The Serializable and Parcelable interfaces can be used to serialize objects. When data is transferred through IntEnts and binders, the user can be serialized in both ways.
  • Serializable belongs to the JAVA API, Parcelable belongs to the Android SDK,
  • Serializable serialization and deserialization processes require significant I/O operations, which Parcelable does not.
  • Serializable has high overhead and low efficiency, and Parcelable vice versa.
  • Serializable is serialized locally or over a network, Parcelable memory serialization

31. Differences between static and non-static inner classes

A non-static inner class implicitly stores a reference to the enclosing enclosing it after compilation, but a static inner class does not.Copy the code

The design intent of static inner classes in Java

Start () and run();

Start (): Starts a new thread that executes the corresponding run() method. Start () cannot be called repeatedly. Run (): Can be called repeatedly, just like normal member methods. Calling run() alone executes run() in the current thread and does not start a new thread!Copy the code

Java advanced part: all understand will be 30K!!

  • In what cases are objects disposed of by the garbage collection mechanism?
  • What are some common ways of coding?
  • Chinese in UTF-8 encoding takes up several bytes; How many bytes of int?
  • What is the difference between static proxy and dynamic proxy?
  • Java’s exception system
  • Talk about your understanding of parsing and dispatching.
  • Change the signature of the equals method of object A. Which equals method will be called when an instance of this object is stored using HashMap?
  • What is the mechanism for implementing polymorphism in Java?
  • How do I serialize a Java object into a file?
  • Tell me what you understand about Java reflection
  • Explain your understanding of Java annotations
  • Tell me what you understand about dependency injection
  • Talk about generics and give some examples
  • Java String understanding
  • Why is String designed to be immutable?
  • Object equal and hashCode methods overwritten. Why?

https://www.jianshu.com/p/c70989bd5f29