Java Interview Topic Collection

Source: Internet
Author: User
Tags float double modifier volatile

There are links to refer to other people's knowledge points.

The 1.equals method is used to compare the object's contents for equality (overwrite later)

The 2.hashcode method is used only in the collection

3. When the Equals method is overridden, the comparison objects are compared by the overridden Equals method (to determine whether the object's contents are equal).

4. When placing an object into a collection, first determine whether the Hashcode value to be placed on the object is equal to the hashcode value of any of the elements in the collection.
If not equal, the object is placed directly into the collection. If the hashcode value is equal, then the Equals method is used to determine the object to be placed in the collection.
Any one object is equal, and if equals is judged unequal, the element is placed directly into the collection, otherwise it is not put.

5. The Equals method is not overridden to determine whether an object is equal by using an object memory address equal.
Because it is two new objects, the memory address of the object is not equal, so Stu1.equals (STU2) is false.

6. Both threads A and b acquire the lock of object o, assuming that a acquires the object o Lock and B waits for a to release the lock on O,
If you use synchronized, if A is not released, B will wait until it cannot be interrupted.
If you use Reentrantlock, if A is not released, you can make B wait long enough to interrupt waiting, while doing something else

    ReentrantLock获取锁定与三种方式:    a)  lock(), 如果获取了锁立即返回,如果别的线程持有锁,当前线程则一直处于休眠状态,直到获取锁    b) tryLock(), 如果获取了锁立即返回true,如果别的线程正持有锁,立即返回false;    c)tryLock(long timeout,TimeUnit unit),   如果获取了锁定立即返回true,如果别的线程正持有锁,会等待参数给定的时间,        在等待的过程中,如果获取了锁定,就返回true,如果等待超时,返回false;    d) lockInterruptibly:如果获取了锁定立即返回,如果没有获取锁定,当前线程处于休眠状态,直到或者锁定,        或者当前线程被别的线程中断    synchronized是在JVM层面上实现的,不但可以通过一些监控工具监控synchronized的锁定,而且在代码执行时出现异常,        JVM会自动释放锁定,但是使用Lock则不行,lock是通过代码实现的,要保证锁定一定会被释放,就必须将unLock()放到finally{}中    在资源竞争不是很激烈的情况下,Synchronized的性能要优于ReetrantLock,但是在资源竞争很激烈的情况下,        Synchronized的性能会下降几十倍,但是ReetrantLock的性能能维持常态;

In the JDK, the Java reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package:
Class: Represents a Class.
Field class: Represents a member variable of a class (a member variable is also called a property of a class).
Method class: Methods that represent classes.
Constructor class: Represents the construction method of a class.
Array class: Provides a static method for dynamically creating an array, and for accessing the elements of an array.

Here are a few examples to look at the practical use of the Reflection API:

Get member variables, member methods, interfaces, superclass, construction methods, etc. through class classes

The

defines the GetClass () method in the Java.lang.Object class, so that for any Java object, the type of the object can be obtained by this method. The class class is the core class in the Reflection API, which has the following methods
GetName (): Gets the full name of the class.
GetFields (): Gets the properties of the public type of the class.
Getdeclaredfields (): Gets all the properties of the class.
GetMethods (): Method that gets the public type of the class.
Getdeclaredmethods (): Gets all the methods of the class.
GetMethod (String name, class[] parametertypes): Gets the specific method of the class, the name parameter specifies the method's first names, and the Parametertypes parameter specifies the method's parameter type.
GetConstructors (): Gets the construction method of the public type of the class.
GetConstructor (class[] parametertypes): Gets the specific constructor method for the class, and the Parametertypes parameter specifies the parameter type of the constructed method.
Newinstance (): Creates an object of this class from the constructor of the class without parameters.
to write a Java Reflector program:
1) You must first get the class object of a category
for example:

 Class c1 = Test.class;  ClassClass.forName(“com.reflection.Test”);  Classnew Test().getClass();

2) Then call the methods in the class object to get the structure of the properties/methods/constructors of a class
Note: If you want to be able to get a normal method/property/constructor in the class, you should focus on the following reflection classes
Field
Constructor
Method

<servlet-mapping><servlet-name></servlet-name><url-pattern></url-pattern></servlet-mapping>
  for(StringELEMENTA:STR) {System.out.print (Elementa +" "); } list<String> list =Newarraylist<String> (); for(intI=0; i<str.length; i++) {if(!list.contains (Str[i]))              {List.add (str[i]); }          }Set<String>Set=Newhashset<String> (); for(intI=0; i<str.length; i++) {Set. Add (Str[i]); }

Spring has six types of transactions five isolation levels

First class: integer byte short int long
Type II: float float double
Class III: Logical Boolean (it has only two values desirable true false)
Class Fourth: Character Char

Methods in the final decorated class
Function: Can be inherited, but cannot be overridden after inheritance.
Final Modifier class
Function: A class cannot be inherited.
The final modification of the basic type when the value is constant, the reference type means that the address is the same, that is, when new is the address can not be re-assigned value
Final modifier properties you know.

Preparestatement is pre-compiled, the SQL is submitted to the database for preprocessing, and then put it into the cache, the next time you find the same will not be compiled,
High execution efficiency, easy to check with syntax hints, parameters are dynamic, prevent SQL injection because syntax checking
SELECT * from tbname = ' zck ' and passwd = ' or ' 1 ' = ' 1 ';
Statement is not precompiled and requires manual check of syntax errors, which are hard-coded

HashMap allows NULL to be a entry key or value, and Hashtable does not allow
Put method
HashMap special handling of NULL value key, always put to table[0] position
The put procedure calculates the hash and then calculates the index value by the hash and table.length, then puts the key to the Table[index] position, and when the other elements exist in Table[index], the Table[index] Position forms a linked list,
Put the newly added element in Table[index], the original element through the entry next link, so as a list to solve the hash conflict problem, when the number of elements reached the critical value (Capactiy*factor),
The table array length changes to Table.length*2
Get method
Also, when key is NULL, special processing is performed, and a null-key element is found on the linked list of table[0]
Get is the process of calculating the hash and then using the hash and table.length to calculate the index value, and then traverse the list on the Table[index],
Until key is found, and then returns
The underlying implementations of HASHMAP and Hashtable are implemented by the array + linked list structure.
Add, delete, get elements are calculated hash first, according to hash and table.length to calculate index is the table array subscript,
And then do the appropriate action

Indexes are mostly based on B-trees

The servlet thread safety problem is primarily caused by instance variables, so you should avoid using instance variables in Servlets.
If application design cannot avoid using instance variables, use synchronization to protect the instance variables to be used, but to ensure the best performance of the system, you should synchronize the code path with the least availability.

Write a single-case pattern

 Public Static Long Recursive(intN) {if(N <=0)return 0;if(n = =1)return 1;returnRecursive (N-1) + Recursive (n-2); } Public Static Long Loop(intN) {if(N <=0)return 0;if(n = =1)return 1;LongFIB1 =0;LongFIB2 =1;Longsum =0; for(inti =2; I <= N;   i++) {sum = fib1 + fib2;   FIB1 = FIB2;  FIB2 = sum; }returnSum }

Hashtable is a thread-safe class that uses synchronized to lock the entire hash table for thread safety.
That is, each time you lock the entire table to allow the thread to monopolize. Concurrenthashmap allows multiple modification operations to be performed concurrently,
The key is the use of lock separation technology. It uses multiple locks to control changes to different parts of the hash table.
Concurrenthashmap Internal Use segment (Segment) to represent these different parts, each segment is actually a small hashtable,
They have their own locks. As long as multiple modification operations occur on different segments, they can be performed concurrently.

Some methods require cross-sections, such as size () and Containsvalue (), and they may need to lock the entire table rather than just a segment.
This requires that all segments be locked sequentially, and the locks for all segments are released sequentially after the operation is complete. Here "in order" is very important,
Otherwise, it is very possible to deadlock, within Concurrenthashmap, the segment array is final, and its member variables are actually final,
However, simply declaring an array as final does not guarantee that the array members are final, which requires implementation assurances.
This ensures that no deadlocks occur because the order in which the locks are obtained is fixed

①threadlocal②synchronized () ③wait () and notify () ④volatile
ThreadLocal
ThreadLocal guarantees that different threads have different instances, and the same thread must have the same instance, which is provided for each thread that uses the variable
A copy of the value of the variable, and each thread can change its own copy independently, instead of conflicting with the copy of the other thread.
Advantage: Provides thread-safe shared objects
Differences from other synchronization mechanisms: The synchronization mechanism is to synchronize multiple threads for concurrent access to the same resource, for communication between multiple threads;
While ThreadLocal is a data share that isolates multiple threads, there is essentially no sharing of resources among multiple threads, so it certainly does not require multiple threads to synchronize.
Volatile
A volatile-modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by the thread. And
When a member variable changes, forcing the thread to write the change back to the shared memory.
Advantage: So at any moment, two different threads always see the same value for a member variable.
Reason: The Java language specification states that in order to get the best speed, a thread is allowed to save a private copy of a shared member variable.
And only when the thread enters or leaves the synchronized code block is it compared to the original value of the shared member variable.
This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the changes to the shared member variables in a timely manner.
The volatile keyword is a hint to the VM: you cannot save its private copy for this member variable, but you should interact directly with the shared member variable.
Usage tip: Use volatile on member variables accessed by two or more threads.
You do not have to use the variable you want to access when it is already in a synchronized code block, or is a constant.
thread to improve efficiency, a member variable (such as a) is copied a copy (such as B),
The access to a in the thread actually accesses B. Synchronization of A and B occurs only in certain actions.
Thus there is a and B inconsistency. Volatile is used to avoid this situation.
Volatile tells the JVM that the variable it modifies does not preserve the copy and accesses the main memory directly
(The read operation is better, the communication between the threads is required, this article cannot do it)
Volatile variables have synchronized visibility characteristics, but they do not have atomic properties.
This means that threads can automatically discover the latest values of volatile variables. Volatile variables can be used to provide thread safety,
But it can only be applied to a very limited set of use cases: there is no constraint between multiple variables or between the current value of a variable and the modified value.
You can use volatile variables instead of locks in a limited number of situations. To make volatile
Variables provide ideal thread safety and must meet the following two conditions:
A write to a variable does not depend on the current value, and the variable is not contained in an invariant that has other variables.
Sleep () vs wait ()
Sleep is a thread-class method that causes this thread to pause execution for a specified time, giving execution opportunities to other threads,
However, the monitoring status is still maintained and will be restored automatically when the time comes. Calling sleep does not release the object lock.
Wait is the method of the object class that calls the wait method on this object to cause the thread to discard the object lock and into the waiting lock pool waiting for the object.
Only after the Notify method (or Notifyall) is emitted for this object does the thread enter the object lock pool ready to get the object lock into the running state.
(If the variable is declared volatile, it will be consistent with main memory every time it is accessed, if the variable is accessed in the synchronization method or synchronization block,
The variable is synchronized when a lock is obtained at the entrance of the method or block, and the lock is released when the method or block exits. )

Http://www.cnblogs.com/zxf330301/p/5634987.html

http://blog.csdn.net/chenssy/article/details/26668941

Http://www.yjbys.com/news/202750.html

The client program has to get the specific container role, and then get the specific iterator role through the specific container role
Iterator it=new arraylist.iterator ();
1) Access the contents of a container object without exposing its internal representation.
2) supports multiple traversal of the container object.
3) provides a unified interface for traversing different container structures (polymorphic iterations).

Constructor is called with the new keyword}→
The constructor is called using the class Newinstance method}→
The constructor is called using the Newinstance method of the constructor class}→
Using the Clone method}→ does not call the constructor
Using deserialization}→ does not call the constructor
Employee EMP2 = (employee) class.forname ("com. Employee "). newinstance ();
Or
Employee emp2 = Employee.class.newInstance ();

Constructor Constructor = Employee.class.getConstructor ();
Employee Emp3 = Constructor.newinstance ();

Using the Clone method, we need to implement the Cloneable interface first and implement its defined clone method
Employee Emp4 = (employee) emp3.clone ();

When the program starts, it does not load all the class files used by the program at once, but is based on the needs of the program.
Loading a class file into memory dynamically via Java's class loading mechanism (ClassLoader)
So that only the class file is loaded into memory,
To be referenced by another class. So ClassLoader is used to dynamically load class files into memory.

Bootstrap ClassLoader: called the Startup class loader, is the topmost class loader in the Java class load hierarchy, responsible for loading the core class library in the JDK,
such as: Rt.jar, Resources.jar, Charsets.jar, etc.
Extension ClassLoader: called the extension ClassLoader, which is responsible for loading the Java Extension Class library,
loads all the jars in the java_home/jre/lib/ext/by default. The
App ClassLoader: called the system ClassLoader, is responsible for loading all the jar and class files in the application Classpath directory.
Because this avoids repeated loading, when the father has loaded the class, there is no need for the ClassLoader to be loaded again.
Given the security factor, let's just imagine that if we don't use this delegate pattern, we can use a custom string to dynamically override the type defined in
the Java Core API at any time, so there's a very big security risk, and the way that parents delegate, you can avoid this situation,
because string has been loaded by the Boot class loader (BOOTSTRCP ClassLoader) at startup,
the user-defined ClassLoader can never load a string that he writes, Unless you change the default algorithm for the ClassLoader search class in the JDK.

1, Request object client requests, this request will contain the parameters from the Get/post request through it to understand the customer's needs, and then respond.
2. The response object responds to customer requests for information
3, Session object it refers to a client-server session, starting from the client connection to a webapplication of the server until the client disconnects from the server.
4. Out object It is an instance of the JspWriter class and is an object commonly used to output content to the client
5, Page object It is to point to the current JSP page itself, a bit like the this pointer in the class, it is an instance of the Java.lang.Object class
6. Application object It realizes the sharing of data among users, and can store global variables. It starts at the start of the server until the server shuts down
7. Exception object It is an exception object, which is generated when a page has an exception during the run.
8. PageContext object It provides access to all objects and namespaces within the JSP page
9. config object it is the JSP engine that passes information to it when a servlet is initialized.

JS has a function IsNaN (val)//If it is a number then return False

There are xmldom parsing, sax parsing, Stax parsing
XMLDOM: (Xmldocumentobjectmodel) The performance of a large file is degraded when it is processed. This problem is caused by the tree structure of the DOM, which takes up more memory, and the DOM must load the entire document into memory before parsing the file, which is suitable for random access to the XML;
SAX: (simpleapiforxml) differs from Dom,sax as an event-driven XML parsing method. It reads the XML file sequentially and does not need to load the entire file at once. When it encounters the beginning of a file, the end of the document, or the end of the label at the beginning of the tag, it triggers an event where the user processes the XML file by writing the processing code in its callback event, suitable for sequential access to the XML;
StAX: The difference between (Streamingapiforxml) and other methods is that the application can handle XML as an event stream, which is superior to other methods in terms of performance and usability;

Thread.getstate ()

Http://blog.chinaunix.net/uid-26602509-id-3306451.html

Java Interview Topic Collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.