[Java] fundamental part of interview questions interview questions

Java basic interview questions

 

The difference between Equals and the ==

Use == Comparison native types such as: boolean ,, int, char etc., using equals () comparison.

1. == type or two variables are determined is not pointing to the same memory space,

It equals the value of two variables are determined or examples points to the memory space is not the same.

2. == refers to the memory address are compared, equals () is compared to the contents of the string

== 3 are the same references refer, equals () refers to the values ​​are identical.

 

Automatic entry boxes

Automatic packing is defined by a Java assignment elementary data type to a variable corresponding class package ,

Unpacking and packing operation is reversed, the variable sucked automatically unpacking a package assigned to the corresponding elementary data types of variables.

 

What work there is a common method Object

Object is the parent class of all classes, default inherit any class Object

Equals In == object with the same subclass typically have to rewrite the method

hashCode The hash lookup method for rewriting the equals method, generally we need to rewrite HashCode method, which is used in some of the Collection with a hash function.

getClass get run-time type

toString method, converted to a string, the sub-class has the general rewritten. Otherwise, printing (memory address) Handle

 

Java four references

As of JDK version 1.2, the reference to the object is divided into four levels, so that the program can be more flexible control of the life cycle of an object, which has four levels high to low order: strong references, soft, weak, references and imaginary references.

  1. 1.     strong references

The most common type of reference, as String s = "abc"; the variable s is the string "abc" strong reference, as long as a strong reference exists, then the garbage collector will not recover the object

  1. 2.     Soft references

There used to describe the use, but not necessarily object if sufficient memory is not recovered, if there is insufficient memory recovery, generally used to implement memory-sensitive told cache, and soft references can be used in conjunction with a reference queue, if you really soft references object is garbage, Jvm will join this soft references associated reference queue

  1. 3.     Weak references

Weak references and soft references roughly the same, the difference between the soft weak references cited are: only a weak reference objects, with more short life cycle, in the course of the garbage collector thread scans the memory area under its jurisdiction, once found only objects with soft references, regardless of the current memory space is sufficient or not, it will reclaim its memory

  1. 4.     phantom reference

Non-existent, and several other references are different, false statement cited period and does not determine the object, if a phantom reference object holds only, and then it does not have any references, are likely to be garbage collected at any time virtual reference primarily used to track objects recovered garbage collector activity.

 

A difference between the virtual reference and references cited in that a soft and weak

Phantom reference must be used in conjunction with a reference queue, when the garbage collector is ready to reclaim an object is, if it is found that there is a virtual reference, it will recover before the memory object, this phantom reference is added to the references associated with the queue.

 

HashCode role

  1. 1.     HashCode features

① HashCode exist primarily for quickness Find As Hashtable, HashMap, etc., HashCode often used to store the address of the object is determined

② If the two objects are the same, equals method will return true, and HashCode necessarily the same two objects

HashCode ③ same two objects, it does not necessarily mean the same two objects, i.e., equals () is not necessarily true, only shows two objects in a hash storage structure

④ If the object equals method is overridden, then the object also try to rewrite HashCode

  1. 2.     HashCode role

There are two types of collections in Java, is a List is a Set, a collection of elements within the former is ordered, the element can be repeated, the latter element does not need, but the elements can not be repeated

Equals methods can be used to ensure the element does not repeat, but if each add an element to check again, if the collection now has 1000 elements, then the first 1001 elements to the collection that should call 1000 equals method, which obviously greatly reduce efficiency, so, Java uses the principle of the hash table

As a result, when the collection you want to add a new element is the first element of this method call HashCode, suddenly able to locate the physical location it should be placed on

① If there is no element in this position, it can be stored directly in this position, we do not have any comparison of

② If you already have an element of this position, call the equals method to compare with new elements, then do not keep the same

③ not identical, that is, the same situation occurred in a conflict of Hash Key, Hash Key then this place will produce a list, all objects will generate the same HashCode into this single-chain up, strung together (rarely ), so that the actual number of calls equals method is greatly reduced, almost need only once or twice.

  1. 3.     How to understand the role of HashCode

From the perspective of Object, JVM each a new Object, it will be the Object throw a Hash table to go, so, next time compared Object or take the object when it will be based HashCode object again from Hash table take this object, veiled aim is to improve the efficiency of taking an object, if HashCode same again call equals

 

String, StringBuffer difference between a StringBuilder

String: apply a small amount of string operations,

StringBuilder situation applies to single-threaded character buffer at a number of things and thread-safe

StringBuilder: the thread is unsafe,

 

The difference between these three classes are mainly in two aspects, namely speed and thread safety of these two aspects, first said running speed, or speed of execution, in this regard speed as the running speed

StringBuilder > StringBuffer > String

String slowest reason

String a string constant, while StringBuilder and StringBuffer are string variables, namely the String object Once created after the objects are immutable, but both objects are variable, that can be changed

 

Thread Safety

On thread-safe StringBuilder is not thread-safe, while StringBuffer is thread-safe

If a StringBuffer object when the string buffer is using multiple threads, StringBuffer in many ways with the synchronized keyword, so you can guarantee thread safe. But StringBuilder method is not the key, it can not guarantee thread safety there may be some wrong operation, so if you want a memory operation is multi-threaded, so long to use StringBuffer, but in single-threaded case, it is recommended to use the faster StringBuilder.

 

Map, Set, List, Queue, Stack features and usage

Map

① Map is a key-value pair, the key Key is the only non-repeating, a key corresponding to a value, the value may be repeated

② TreeMap can guarantee the order

③ HashMap not guarantee the sequence, i.e. disordered

④ Map Key and Value can be individually extracted, wherein KeySets () method may be drawn into an all Key Set, and Values ​​() method may be drawn into the Map of all a set of Values

Set

① not contain duplicate set, set up a Null element contains

② can only be achieved with a single traversal Letrator, Set there is no synchronization method.

List

① duplicate set of ordered

② can add or delete elements in any position

③ with a single traversal iterator to achieve, you can also use two-way traverse ListIterator

Queue

① Queue follow the FIFO principle

② avoid the use of add () and remove () method, but the use of the offer () to add elements, using Poll () to removed the element, it has the advantage can be judged by whether the return value success

③ LinkedList implements Queue Interface

④ Queue typically inserted Null elements are not allowed

Stack

① Stack comply with the principle of LIFO

② Stack inherited from Vector

③ It is by operation of the class Vector five expand, allowing the vector considered stack, which offers the usual Push and POP operations, and the point stack peek () method to test whether the stack is empty empty method

usage

① If the operation involves stacks, queues, etc., it is recommended to use List

② for quick insert and delete elements, it is recommended to use LinkedList

③ If you need fast random access to the elements, it is recommended to use ArrayList

More refined summary

Collection is a collection of objects, Collection has two sub-interfaces, List, and Set

       List by index values ​​may be (1,2,3 ..), the value may be repeated, Set values ​​can only be by the cursor, and the value is not repeated

       ArrayList, Vector, LinkedList List is the implementation class

       ArrayList is not thread-safe, Vector is thread-safe, these two classes are implemented by the underlying array

       LinkedList is not thread-safe, the bottom is achieved by a linked list

Map is a collection of key-value pairs

① HashTable and HashMap implementation class is a Map

② HashTable are thread-safe, you can not store Null value

③ HashMap is not thread-safe and can be stored Null 'values

 

Stack class

       Inherited from Vector, to implement a LIFO stack that provides a few basic methods, push, pop, peak, empty, search, etc.

Queue class

       Provides several basic methods, offer, poll, peek, etc., have been implementing class LinkedList, PriorityQueue etc.

 

Try catch finally try there return, finally will be implemented?

Will certainly be executed, finally {} block of code, containing only encountered System.exit (), leading to the Java virtual machine to exit statement like will not perform in the try {} block.

When the try {} after the program execution encounters return, the program will first execute a return statement, but did not immediately return eleven is the return statement do some things ready, that is to be returned, but when returned, the program execution flow vector to the finally block, the finally block after the execution is complete when the direct return statement has been prepared just returned good results.

 

Java (OOP) object-oriented features of the three meanings

Package (high cohesion and low coupling à decoupled)

Packaging refers to packaging properties and behavior of something into an object, the object is only released to external attributes and behavior need to be exposed, and this announcement may also selectively released to other objects in java can use the private, protected , public three kinds of modifiers or not (which is the default defalut) to access external object attributes and behavior of the object limit

.

Java inheritance (reuse parent class code)

Inheritance is a child object can inherit the properties and behavior of the parent, that parent has the properties and behavior of its children will have these attributes and behaviors

Polymorphism in Java (parent class to sub-class object reference)

Polymorphism refers to the behavior of the same parent object can be multiple sub-objects in its different manifestations by

There are two mechanisms of polymorphism: compile-time polymorphism, run-time polymorphism

  1. Method overloading; refers to reload a plurality of the same name in the same class of methods, but these methods have different parameters, it can be determined at compile time which method calls in the end, which is compiling a polymorphism at
  2. Rewrite process: a subclass can override the parent class method, so the same method will have different manifestations in the parent class and subclass 

Meaning the difference between the Override and Overload

Overload Overload same method name, a list of different parameters (number, order, different types of) independent of the return type.

Rewrite Override cover covering the parent class rewriting rewriting method: the same method name can only access modifiers is greater than the access modifier method is overridden, the method name, the order number of the same type

Override (rewrite)

  1. Method name, arguments, return the same value.
  2. Subclass method can not be reduced access to the parent class method
  3. Subclass method can not throw more than the parent class method exceptions (but subclass method can not throw an exception)
  4. It exists between the parent and child classes
  5. Is defined as the final method can not be rewritten

Overload (overload)

  1. Parameter type, the number, not the same as the order of at least one
  2. 2.     not be overloaded simply returns a different value method name
  3. Present in the parent class and subclass, in the same

Overloaded rules

  1. There must be a different parameter list
  2. Can have different return types, as long as the list of different parameters on it
  3. You can have different access modifiers
  4. You can throw different exceptions

Rewrite the rules of method

  1. Parameter list must be exactly the same as the method is overridden, otherwise it could not be called rewrite but overloaded
  2. The return type must always return the same type of method is overridden, otherwise it could not be called rewrite but overloaded
  3. Restricted access modifier must be greater than the access modifier is rewritten method (public> protected> default> private )
  4. Overriding methods must not throw new or checked exceptions than the overridden method is declared broader checked exceptions

Interface difference between abstract classes

Interface only member variables can only be declared method

Abstract class can have member variables, methods and general method can be declared abstract

Interface is the interface

All methods are abstract, member variables public static final is the default type of interface can not be instantiated own

Abstract class is an abstract class, the class that contains at least one abstract method called abstract class, abstract class can not be instantiated themselves, and with the abstract keyword to modify

AOP What is

AOP Oriented Programming is a hot software development, the Spring Framework content, using AOP can each part of the business logic of the isolation, so that the business logic parts of the coupling is reduced, improving program reusable type, to improve development efficiency, main features: logging, performance statistics, security control, transaction processing, exception handling.

OOP What is

OOP object-oriented programming, encapsulation abstract entities and attributes and behaviors for the business process to obtain a clearer division efficient logic unit

AOP difference between the OOP

When OOP object-oriented programming, abstraction and encapsulation for the entities and their attributes behavior of the business process, to obtain a clearer division efficient logic unit, and AOP is extracted for the business process section, it faces a step or stage of the process to isolate the effect of a low logic coupling procedure between the parts in these two essentially different design on the target

For example:

For an example of such a business "employee" for physical package, is naturally the task of OOP, we can build a "Employee" category, and "employee" related attributes and behaviors package which, while AOP design of "employee" from the encapsulates it is the question

Similarly, for "permission check" This action segments are divided, it is the goal of AOP field

OOP term oriented art, AOP field for verbs

In short AOP proxy can be dynamically by way of pre-compiled and run to achieve. Dynamically added to the program in a technology function without modifying source code.

Java open thread method

Thread class inheritance and implement Runnable interface, Java can not be achieved due to the multiple inheritance, it is generally to create a thread by implementing Runnable interface. But no matter which method are available through the start () and run () method to start a thread, Here's to introduce them difference

Start method

By this method the same time start the thread also creates a thread, truly multi-threaded, without waiting for the run () method in the code execution is complete, you can then execute the code below, then start () this thread in the ready state, when the CPU time slice is obtained, which executes run () method. the run () method contains the contents of the thread to be executed, the end of the run () method runs, this thread will cease ..

Run method:

By calling the run method is actually a method to start the thread class, as a normal way of method calls, and did not create a thread, the program is still only one main thread must wait until the run () method inside the code is completed, will continue execute the following code, so there is no purpose to write thread 

Thread class inheritance and implement Runnable can define a thread. Difference, what does?

Runnable interface to achieve the advantages

  1. Avoid Java single inheritance issues
  2. Suitable for multi-threaded processing the same resources
  3. Multi-threaded code that can be shared, data-independent, it is easy to share resources

Summary :

  1. start () can start a new thread, run () can not
  2. start () can not be called repeatedly, run () can
  3. start run the code () can not perform the play to continue the implementation of the code below, that is a thread switch directly call run method must wait for all of their code in order to continue executing the following code execution
  4. start () to achieve a multi-threaded, run () does not implement multithreading

 

Guess you like

Origin www.cnblogs.com/yanglichen/p/11599552.html