Java basics:
0. The difference between scope public, private, protected, and not writing
Answer: The differences are as follows:
Scope Current class Same package Subgenital class Other packages
public √ √ √ √
protected √ √ √ ×
friendly √ √ × ×
private √ × × ×
Default is friendly when not writing
1。
Classes are of final type, so this class cannot be inherited or modified. In order to improve efficiency and save space, we should use the StringBuffer class
3. What is the difference between int and Integer
Java provides two different types: reference type and primitive type (or built-in type). Int is the original data type of java, and Integer is the encapsulated class provided by java for int. Java provides encapsulated classes for each primitive type.
Primitive type encapsulation class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
Reference types behave completely differently from primitive types, and they have different semantics. Reference types and primitive types have different characteristics and usages, including: size and speed issues, which type of data structure this type is stored, and the default value specified when the reference type and primitive types are used as instance data for a certain class. The default value of an object reference instance variable is null, while the default value of the original type instance variable is related to their type.
4. The difference between String and StringBuffer
The JAVA platform provides two classes: String and StringBuffer, which can store and manipulate strings, namely character data containing multiple characters. This String class provides strings whose values are unchangeable. The string provided by this StringBuffer class is modified. When you know that the character data is to be changed, you can use StringBuffer. Typically, you can use StringBuffers to dynamically construct character data.
5. What are the similarities and differences between runtime exceptions and general exceptions?
Exceptions represent abnormal states that may occur during the program operation. Runtime exceptions represent exceptions that may be encountered during the normal operation of the virtual machine, which is a common operation error. The java compiler requires that the method must declare that a non-runtime exception that may occur, but does not require that the uncatched runtime exception must be declared.
6. Talk about the life cycle of a servlet and tell the difference between servlet and CGI.
After the servlet is instantiated by the server, the container runs its init method, and runs its service method when the request arrives. The service method automatically dispatches and runs the doXXX method (doGet, doPost) corresponding to the request, etc., and calls its destroy method when the server decides to destroy the instance.
The difference with cgi is that the servlet is in the server process. It runs its service method through multi-threading. An instance can serve multiple requests, and its instance is generally not destroyed. CGI generates a new process for each request, and it is destroyed after the service is completed, so it is lower than the servlet in efficiency.
7. Tell the storage performance and characteristics of ArrayList, Vector, and LinkedList
ArrayList and Vector both use arrays to store data. The number of elements in this array is larger than the actual stored data to add and insert elements. They both allow the indexing of elements directly by sequence number. However, inserting elements involves memory operations such as array element movement, so indexing data is fast and inserting data is slow. Vector uses synchronized method (thread safety), and performance is usually worse than ArrayList. LinkedList uses a bidirectional linked list to store. Indexing data by sequence number requires forward or backward traversal, but when inserting data, only the front and back items of this item are recorded, so the insertion speed is faster.
8. What technologies are implemented based on EJB? And tell us the difference between SessionBean and EntityBean, and the difference between StatefulBean and StatelessBean.
EJB includes Session Bean, Entity Bean, Message Driven Bean, and is implemented based on technologies such as JNDI, RMI, and JAT.
SessionBean is used in J2EE applications to complete some server-side business operations, such as accessing databases and calling other EJB components. EntityBean is used to represent data used in the application system.
For clients, SessionBean is a non-persistent object that implements some business logic running on the server.
For clients, EntityBean is a persistent object that represents an object view of an entity stored in persistent memory, or an entity implemented by an existing enterprise application.
Session Beans can also be further subdivided into Stateful Session Beans and Stateless Session Beans. Both of these Session Beans can execute system logic in the method. The difference is that Stateful Session Beans can record the status of the caller. Therefore, generally speaking, a user will have a corresponding Stateful Session Bean entity. Although the Stateless Session Bean is also a logical component, it is not responsible for recording the user's status. That is to say, when the user calls the Stateless Session Bean, the EJB Container will not look for a specific Stateless Session Bean entity to execute this method. In other words, it is very likely that when several users execute methods of a Stateless Session Bean, the Instance of the same bean will be executed. From the memory perspective, compared with Stateful Session Bean, Stateful Session Bean consumes more memory from J2EE Server, but the advantage of Stateful Session Bean is that it can maintain the user's state.
9. The difference between Collection and Collections.
Collection is the upper-level interface of the collection class, and its main interfaces are Set and List.
Collections is a help class for collection classes. It provides a series of static methods to implement search, sorting, thread-safe operations on various collections.
10. The difference between & &&.
& is a bit operator, representing bitwise and operation, and && is a logical operator, representing logic and (and).
11. The difference between HashMap and Hashtable.
HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation). They all complete the Map interface. The main difference is that HashMap allows null keys. Due to non-thread-safe, it may be more efficient than Hashtable.
HashMap allows null as a key or value of an entry, while Hashtable does not.
HashMap removes the Hashtable contains method and changes it to containsvalue and containsKey. Because the contains method is easy to cause misunderstanding.
Hashtable inherits from the Dictionary class, and HashMap is an implementation of Map interface introduced by Java 1.2.
The biggest difference is that the Hashtable method is Synchronize, while HashMap is not. When multiple threads access Hashtable, they do not need to implement synchronization for its methods themselves, and HashMap must provide external synchronization for it.
The hash/rehash algorithms used by Hashtable and HashMap are roughly the same, so there will be no big difference in performance.
12. The difference between final, finally, finalize.
final is used to declare attributes, methods and classes, respectively, indicating that attributes are immutable, methods cannot be overwritten, and classes cannot be inherited.
Finally is part of the exception handling statement structure, indicating that it is always executed.
Finalize is a method of the Object class. This method of the recycled object will be called when the garbage collector executes. This method can override other resource recycling during garbage collection, such as closing files, etc.
13. What is the difference between sleep() and wait()?
sleep is a method of the thread class (Thread), causing this thread to pause execution for a specified time and give execution opportunities to other threads, but the monitoring status remains and will automatically resume after that. Calling sleep will not release the object lock.
wait is a method of the Object class. Calling the wait method on this object causes the thread to give up the object lock and enter the waiting lock pool waiting for this object. Only after issuing a notify method (or notifyAll) for this object, this thread enters the object lock pool and prepares to obtain the object lock and enters the running state.
14. The difference between Overload and Override. Can the Overloaded method change the type of return value??
Overriding and overloading of methods are different manifestations of Java polymorphism. Overriding is a manifestation of polymorphism between parent and child class, and overloading is a manifestation of polymorphism in a class. If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overriding. When the object of the subclass uses this method, the definition in the subclass will be called. For it, the definition in the parent class is as if it is "masked". If multiple methods with the same name are defined in a class, they have different number of parameters or different parameter types, it is called overloading of the method. The Overloaded method can change the type of return value.
15. What is the difference between error and exception?
error means that recovery is not an impossible but difficult situation. For example, memory overflow. It is impossible to expect the program to handle such a situation.
Exception represents a design or implementation problem. That is, it means that if the program runs properly, it never happens.
16. What are the similarities and differences between synchronization and asynchronous, and under what circumstances do they use separately? Give an example.
If the data will be shared between threads. For example, the data being written may be read by another thread in the future, or the data being read may have been written by another thread, so this data is shared data and must be accessed synchronously.
When an application calls a method on an object that takes a long time to execute and does not want the program to wait for the method to return, asynchronous programming should be used, and in many cases, it is often more efficient to adopt an asynchronous approach.
17. What is the difference between abstract class and interface?
A class that declares the existence of a method without implementing it is called an abstract class. It is used to create a class that embodies certain basic behaviors and declare methods for that class, but cannot implement the class in that class. An instance of the abstract class cannot be created. However, a variable can be created whose type is an abstract class and let it point to an instance of a concrete subclass. There cannot be abstract constructors or abstract static methods. Subclasses of Abstract class provide implementations for all abstract methods in their parent class, otherwise they are also abstract classes. Instead, implement the method in a subclass. Other classes that know their behavior can implement these methods in the class.
An interface is a variant of an abstract class. In an interface, all methods are abstract. Multiple inheritance can be obtained by implementing such an interface. All methods in the interface are abstract, and none have a program body. Interfaces can only define static final member variables. The implementation of an interface is similar to a subclass except that the implementation class cannot inherit behavior from the interface definition. When a class implements a special interface, it defines (i.e., gives the program body) methods of all such interfaces. It can then call the interface's methods on any object of the class that implements the interface. Because of the abstract class, it allows the use of interface names as the type of reference variables. The usual dynamic linkage will take effect. References can be converted to or from interface type, and the instanceof operator can be used to determine whether an object's class implements an interface.
18. What is the difference between heap and stack.
A stack is a linear collection, and the operations to add and delete elements should be completed in the same section. The stack is processed in the first-out mode.
Heap is a component element of the stack
19. The difference between forward and redirect
forward is the server requests resources. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends the content to the browser. The browser has no idea where the content sent by the server comes from, so its address bar is still the original address.
Redirect means that the server sends a status code based on the logic and tells the browser to request the address again. Generally speaking, the browser will re-request with all the parameters requested just now, so the session and request parameters can be obtained.
20. What is the difference between EJB and JAVA BEAN?
Java Beans are reusable components and do not have strict specifications for Java Beans. In theory, any Java class can be a bean. But usually, since Java Beans are created by containers (such as Tomcat), Java Beans should have a constructor without parameters. In addition, Java Beans usually implement the Serializable interface to achieve the persistence of the Bean. Java Bean is actually equivalent to a local in-process COM component in the Microsoft COM model, and it cannot be accessed across processes. Enterprise Java Bean is equivalent to DCOM, that is, distributed components. It is based on Java's remote method call (RMI) technology, so EJB can be accessed remotely (cross-process, cross-computer). But EJB must be deployed in containers such as Webspere and WebLogic. EJB customers never directly access real EJB components, but access them through their containers. EJB containers are agents of EJB components, and EJB components are created and managed by containers. The client accesses the real EJB component through the container.
21. The difference between Static Nested Class and Inner Class.
Static Nested Class is an inner class declared as static, which can be instantiated without relying on external class instances. The usual inner class needs to be instantiated after the outer class is instantiated.
22. What is the difference between dynamic INCLUDE and static INCLUDE in JSP?
Dynamic INCLUDE is implemented using jsp:include action
It always checks for changes in the included files, is suitable for including dynamic pages, and can be parameterized.
Static INCLUDE is implemented with include pseudo code, which will definitely not check the changes of the included files, and is suitable for static pages.
23. When to use assert.
assertion is a commonly used debugging method in software development, and many development languages support this mechanism. In implementation, assertion is a statement in the program that checks a boolean expression. A correct program must ensure that the value of this boolean expression is true; if the value is false, it means that the program is already in an incorrect state, and the system will give a warning or exit. Generally speaking, assertion is used to ensure the most basic and critical correctness of the program. Assertion checks are usually turned on during development and testing. To improve performance, assertion checks are usually turned off after software release.
24. What is GC? Why do you needGC?
GC means garbage collection (Gabage Collection). Memory processing is a place where programmers are prone to problems. Forgot or incorrect memory recycling will cause instability or even crashes in the program or system. The GC function provided by Java can automatically monitor whether the object exceeds the scope to achieve the purpose of automatically reclaiming memory. The Java language does not provide a display operation method for freeing allocated memory.
25. Short s1 = 1; s1 = s1 + 1; What's wrong? short s1 = 1; s1 += 1; What's wrong?
short s1 = 1; s1 = s1 + 1; (The result of s1+1 operation is int type, and a cast type is required)
short s1 = 1; s1 += 1; (can be compiled correctly)
26. What is (11.5) equal to? (-11.5) equal to what is?
(11.5)==12
(-11.5)==-11
The round method returns the long integer closest to the parameter. After adding 1/2 to the parameter, find its floor.
27. String s = new String("xyz"); several createdString Object?
two
28. Design 4 threads, two threads increase by 1 each time for j, and the other two threads decrease by 1 each time for j. Write out the program.
The following program uses internal classes to implement threads, and does not consider the order issue when adding or decreasing j.
public class ThreadTest1{
private int j;
public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc= Inc();
Dec dec= Dec();
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
();
t=new Thread(dec);
();
}
}
private synchronized void inc(){
j++;
(().getName()+"-inc:"+j);
}
private synchronized void dec(){
j--;
(().getName()+"-dec:"+j);
}
class Inc implements Runnable{
public void run(){
for(int i=0;i<100;i++){
inc();
}
}
}
class Dec implements Runnable{
public void run(){
for(int i=0;i<100;i++){
dec();
}
}
}
}
29. Is there any Javagoto?
The reserved words in java are not used in java now.
30. Should I use run() or start a thread?start()?
Starting a thread is to call the start() method, so that the virtual processor represented by the thread is in an runnable state, which means it can be scheduled and executed by the JVM. This does not mean that the thread will run immediately. The run() method can generate a flag that must be exited to stop a thread.
31. EJB includes (SessionBean, EntityBean) to tell their life cycle and how to manage transactions?
SessionBean: The life cycle of a Stateless Session Bean is determined by the container. When the client issues a request to establish an instance of a bean, the EJB container does not necessarily create a new instance of the bean for the client to call, but simply finds an existing instance to provide it to the client. When the client calls a Stateful Session Bean for the first time, the container must immediately create a new bean instance in the server and associate it with the client. Later, when this client calls the Stateful Session Bean method, the container will dispatch the call to the bean instance associated with the client.
EntityBean: Entity Beans can survive for a relatively long time and their state is continuous. Entity beans will survive as long as the data in the database exists. Not according to the application or service process. Even if the EJB container crashes, Entity beans survive. The Entity Beans life cycle can be managed by containers or beans themselves.
EJB manages practices through the following technologies: Object Management Organization (OMG) Object Practice Service (OTS), Sun Microsystems' Transaction Service (JTS), Java Transaction API (JTA), and XA interface of development group (X/Open).
32. What application servers are there?
BEA WebLogic Server,IBM WebSphere Application Server,Oracle9i Application Server,jBoss,Tomcat
33. Give me the runtime exception you see most often.
ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IndexOutOfBoundsException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, ProfileDataException, ProviderException, RasterFormatException, SecurityException, SystemException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException
34. Can an interface be inherited from an interface? Can an abstract class implement the interface? Can an abstract class inherit from an entity class(concrete class)?
Interfaces can inherit interfaces. Abstract classes can implement (implements) interfaces. Whether abstract classes can inherit entity classes, but the premise is that the entity classes must have a clear constructor.
35. Whether List, Set, Map inherits from the Collection interface?
List, Set is, Map is not
36. Tell what is the working mechanism of the data connection pool?
A certain number of pooled connections will be established when the J2EE server is started and a certain number of pooled connections will be maintained at all times. When a client program needs to connect, the pool driver returns an unused pool connection and tables it as busy. If there is currently no idle connection, the pool driver creates a certain number of new connections, and the number of new connections is determined by configuration parameters. When the pool connection call used is completed, the pool driver will record the connection table as free, and other calls can use this connection.
37. Can abstract method be static at the same time, can it be native at the same time, and can it besynchronized?
None of them
38. Is there a length() method for arrays? Is there a length() method for String?
The array does not have the length() method, but has the length attribute. String has the method length().
39. The elements in the Set cannot be repeated, so what method should be used to distinguish whether they are repeated or not? Should I use == or equals()? What is the difference between them?
The elements in the Set cannot be repeated, so use the iterator() method to distinguish whether it is repeated or not. equals() is to determine whether two Sets are equal.
The equals() and == methods determine whether the reference value points to the same object equals() is overwritten in the class, so that when the content and type of the two separate objects match, the true value is returned.
40. Can the constructor beoverride?
The constructor constructor cannot be inherited, so Overriding cannot be overridden, but Overloading can be overloaded.
41. Can you inherit the String class??
The String class is a final class, so it cannot be inherited.
42. Whether swtich can act on byte, whether it can act on long, and whether it can act on String?
In switch(expr1), expr1 is an integer expression. Therefore, the parameters passed to the switch and case statements should be int, short, char or byte. Neither long nor string can act on swtich.
43. There is a return statement in try {}. Then will the code in finally {} immediately following this try be executed, when will it be executed, before or after return?
Will execute, before return.
44. Programming questions: Use the most efficient method to calculate what is 2 times 8 equal to?
2 << 3
45. Two objects have the same value ((y) == true), but they can have different hash codes. Is this correct??
No, there is the same hash code.
46. When an object is passed as a parameter to a method, this method can change the properties of the object and return the changed result. So is it a value or a reference passed here??
is value passing. The Java programming language only passes parameters with values. When an object instance is passed into a method as a parameter, the value of the parameter is a reference to the object. The content of an object can be changed in the called method, but the reference of the object will never change.
47. When a thread enters a synchronized method of an object, can other threads enter other methods of this object??
No, a synchronized method of an object can only be accessed by one thread.
48. Programming questions: Write a Singleton.
The main function of the Singleton pattern is to ensure that in Java applications, only one instance of a class exists.
The general Singleton mode usually has several forms:
The first form: defines a class whose constructor is private. It has a static private variable of the class. When the class is initialized, the instance uses a public getInstance method to obtain a reference to it, and then call the method in it.
public class Singleton {
private Singleton(){}
//Isn’t it strange to define an instance of yourself inside yourself?
//Note that this is private only for internal calls
private static Singleton instance = new Singleton();
// Here is a static method for external access to this class, which can be accessed directly
public static Singleton getInstance() {
return instance;
}
}
The second form:
public class Singleton {
private static Singleton instance = null;
public static synchronized Singleton getInstance() {
//This method is improved over the above. You don’t need to generate objects every time, it’s just the first time
//Create instances when used, improve efficiency!
if (instance==null)
instance=new Singleton();
return instance; }
}
Other forms:
Define a class whose constructor is private and all methods are static.
Generally, it is believed that the first form is safer
49. The same and differences between Java's interface and C++'s virtual classes.
Since Java does not support multiple inheritance, it is possible that a certain class or object needs to use methods or attributes in several classes or objects, the existing single inheritance mechanism cannot meet the requirements. Interfaces have higher flexibility than inheritance because there is no implementation code in the interface. When a class implements an interface, the class needs to implement all methods and properties in the interface, and the properties in the interface are public static under the default state, and all methods are public by default. A class can implement multiple interfaces.
50. Simple principles and applications of exception handling mechanism in Java.
When a JAVA program violates JAVA semantic rules, the JAVA virtual machine will represent the error that occurs as an exception. Violation of semantic rules includes 2 cases. One is the built-in semantic checking of the JAVA class library. For example, if an array subscript exceeds the bounds, an IndexOutOfBoundsException will be raised; a NullPointerException will be raised when accessing a null object. Another situation is that JAVA allows programmers to extend this semantic checking, which allows programmers to create their own exceptions and freely choose when to throw an exception with the throw keyword. All exceptions are subclasses of .
51, advantages and principles of garbage recycling. And consider2type of recycling mechanism.
A significant feature of the Java language is the introduction of a garbage collection mechanism, which can solve the most troublesome memory management problem of C++ programmers. It makes Java programmers no longer need to consider memory management when writing programs. Due to a garbage collection mechanism, objects in Java no longer have the concept of "scope", and only references to objects have "scope". Garbage collection can effectively prevent memory leakage and effectively use the available memory. The garbage collector is usually run as a separate low-level thread. It is unpredictable to clearly and recycle objects that have died or have not been used for a long time in the memory heap. Programmers cannot call the garbage collector in real time to garbage collect one or all objects. The recycling mechanism includes generational replication garbage collection, labeled garbage collection, and incremental garbage collection.
52, please tell us what you know about thread synchronization methods.
wait(): Makes a thread in a waiting state and releases the lock of the held object.
sleep(): Make a running thread sleep state, it is a static method, and call this method to catch the InterruptedException exception.
notify(): Wake up a thread in a waiting state. Note that when calling this method, it cannot exactly wake up a thread in a waiting state. Instead, the JVM determines which thread to wake up, and it does not depend on priority.
Allnotity(): Wake up all threads in waiting state, note that it is not to give all the wake-up threads an object lock, but to let them compete.
53, What collection classes do you know? Main method?
The most commonly used collection classes are List and Map. The specific implementation of List includes ArrayList and Vector, which are variable-sized lists that are more suitable for building, storing, and manipulating lists of elements of any type of object. List is suitable for accessing elements by numerical indexing.
Map provides a more general method of element storage. The Map collection class is used to store element pairs (called "keys" and "values") where each key maps to a value.
54, describe itJVMloadclassThe principle and mechanism of the file?
Class loading in JVM is implemented by ClassLoader and its subclasses. Java ClassLoader is an important Java runtime system component. It is responsible for finding and loading classes of class files at runtime.
55、charCan a Chinese character be stored in a type variable??Why?
It can be defined as a Chinese, because unicode is encoded in Java, and a char takes up 16 bytes, so it is no problem to put a Chinese
56, There are several implementation methods for multi-threading,What are they?There are several ways to implement synchronization,What are they?
There are two implementation methods for multi-threading, namely inheriting the Thread class and implementing the Runnable interface.
There are two types of synchronization implementation, namely synchronized, wait and notify
57、JSPbuilt-in objects and methods.
request represents the HttpServletRequest object. It contains information about browser requests and provides several useful methods for obtaining cookie, header, and session data.
Response represents the HttpServletResponse object and provides several methods for setting the response sent back to the browser (such as cookies, header information, etc.)
The out object is an instance and provides several methods that allow you to use to loop back the output result to the browser.
pageContext represents an object. It is an API for easy access to namespaces and servlet-related objects in various scopes, and wraps common servlet-related functions.
session represents a requested object. Session can store user status information
applicaton represents an object. This helps find information about the servlet engine and servlet environment
config represents an object. This object is used to access the initialization parameters of the servlet instance.
Page represents a servlet instance generated from the page
58, basic concepts of threads, basic states of threads and relationships between states
A thread refers to an execution unit that can execute program code during program execution. Each program has at least one thread, that is, the program itself.
There are four states of threads in Java: run, ready, suspend, and end.
59、JSPCommon instructions
isErrorPage (whether the Exception object can be used), isELIgnored (whether the expression is ignored)
" target="_blank">http://......"%>
60, under what circumstances should I calldoGet()anddoPost()?
When the method property in the form tag in the Jsp page is get, doGet() is called, and doPost() is called when it is post.
61、servletLife cycle
The web container loads the servlet and the life cycle begins. Initialize the servlet by calling the init() method of the servlet. Implemented by calling the service() method, different do***() methods are called according to different requests. End the service, the web container calls the destroy() method of the servlet.
62, how to be realisticservletSingle threaded mode
63, Methods of object transfer between pages
Request, session, application, cookie, etc.
64、JSPandServletWhat are the similarities and differences, and what is the connection between them?
JSP is an extension of Servlet technology. It is essentially a simple way of Servlet, and emphasizes the appearance of the application. After JSP is compiled, it is "class servlet". The main difference between Servlet and JSP is that the application logic of Servlet is in Java files and is completely separated from the HTML in the presentation layer. The case of JSP is that Java and HTML can be combined into a file with the extension .jsp. JSP focuses on views, and Servlets are mainly used for control logic.
65, four conversation tracking technologies
Session Scope ServletsJSP Page Description
Whether the page represents objects and properties related to a page. A page is represented by a compiled Java servlet class (can take any include directives, but no include action). This includes both the servlet and the JSP pages compiled into the servlet
The request is an object and property that represents a request related to a request issued by the Web client. A request may span multiple pages, involving multiple web components (due to the relationship between forward directives and include actions)
The session is an object and property that represents a user experience for a certain Web client. A web session can and often requests across multiple client machines
Application is an object and property that represents the entire web application. This is essentially a global scope across the entire web application, including multiple pages, requests, and sessions
66、RequestThe main methods of the object:
setAttribute(String name,Object): Set the parameter value of the request with name name
getAttribute(String name): Returns the attribute value specified by name
getAttributeNames(): Returns the name set of all attributes of the request object, and the result is an enumeration instance
getCookies(): Returns all cookie objects of the client, and the result is an array of cookies
getCharacterEncoding(): Returns the character encoding method in the request
getContentLength(): Returns the length of the requested Body
getHeader(String name): Get the file header information defined by the HTTP protocol
getHeaders(String name): Returns all values of the request header with the specified name, and the result is an enumeration instance
getHeaderNames(): Returns the name of the request Header, and the result is an enumeration instance
getInputStream(): Returns the requested input stream, used to obtain the data in the request
getMethod(): Get the method to transfer data to the server by the client
getParameter(String name): Get the parameter value specified by name sent by the client to the server
getParameterNames(): Get the names of all parameters sent by the client to the server, and the result is an enumeration instance
getParameterValues(String name): Get all values of the parameter specified by name
getProtocol(): Get the protocol name based on which the client transmits data to the server
getQueryString(): Get query string
getRequestURI(): Get the client address of the request string that issued
getRemoteAddr(): Get the IP address of the client
getRemoteHost(): Get the client's name
getSession([Boolean create]): Returns the Session related to the request
getServerName(): Get the server's name
getServletPath(): Get the path to the script file requested by the client
getServerPort(): Get the port number of the server
removeAttribute(String name): Remove an attribute in the request
67、J2EEIs it a technology, a platform or a framework?
J2EE itself is a standard, a standard platform for the development of enterprise distributed applications.
J2EE is also a framework, including JDBC, JNDI, RMI, JMS, EJB, JTA and other technologies.
68, We are herewebDuring application development, we often encounter characters that output some kind of code, such asiso8859-1Wait, how to output a string of some kind of encoded?
Public String translate (String str) {
String tempStr = "";
try {
tempStr = new String(("ISO-8859-1"), "GBK");
tempStr = ();
}
catch (Exception e) {
(());
}
return tempStr;
}
69, briefly describe logical operations(&,|,^)and conditional operations(&&,||)The difference.
The main answers are two points: a. Conditional operations can only operate Boolean, while logical operations can not only operate Boolean, but also operate numerical types.
b. Logical operations will not cause short circuits
70、XMLHow many forms are there in document definition? What is the essential difference between them? AnalysisXMLWhat are the ways to do documentation?
a: Two forms dtd schema
b: Essential difference: schema itself is xml and can be parsed by an XML parser (this is also the fundamental purpose of developing schema from DTD)
c: There are DOM, SAX, STAX, etc.
DOM: When processing large files, its performance declines very significantly. This problem is caused by the tree structure of the DOM, which occupies a lot of memory, and the DOM must load the entire document into memory before parsing the file, which is suitable for random access to XML
SAX: Not present in DOM, SAX is an event-driven XML parsing method. It reads XML files in sequence and does not require the entire file to be loaded at once. When encountering an event like the beginning of a file, the end of a document, or the beginning of a tag and the end of a tag, it triggers an event, and the user processes the XML file by writing processing code in its callback event, suitable for sequential access to XML
STAX:Streaming API for XML (StAX)
There are two ways to define the XML document:
dtd: data type definition, used to describe the document structure of XML documents, is an early XML document definition form.
schema: It is written in XML language, and its type and syntax limitation ability is stronger than dtd, and it is more convenient to process, because this is gradually replacing dtd as a new schema definition language.
71, brief descriptionsynchronizedandSimilarities and similarities ?
The main similarities: Lock can complete all functions implemented by synchronized
Key differences: Lock has more precise thread semantics and better performance than synchronized. synchronized will automatically release the lock, and Lock must require the programmer to release it manually and must be released in the finally clause.
72、EJBRoles and three objects
A complete distributed computing structure based on EJB is composed of six roles that can be provided by different developers. Each role must follow the EJB specifications provided by Sun to ensure compatibility with each other. These six roles are EJB component developer (Enterprise Bean Provider), Application Assembler, Deployer, EJB Server Provider, EJB Container Provider, and System Administrator
The three objects are the Remote (Local) interface, the Home (LocalHome) interface, and the Bean class
73、EJBServices provided by containers
It mainly provides services such as declaration cycle management, code generation, continuous management, security, transaction management, locking and concurrent issuance management.
74、EJBSpecificationsEJBWhat are the prohibited operations in?
1. Cannot operate threads and thread APIs (thread API refers to methods that are non-thread objects such as notify, wait, etc.), 2. Cannot operate awt, 3. Cannot implement server functions, 4. Cannot survive and retrieve static attributes, 5. Cannot use IO operations to directly access the file system, 6. Cannot load local libraries., 7. Cannot use this as a variable and return, 8. Cannot call it loop.
75、remoteInterface andhomeThe main function of the interface
The remote interface defines business methods for EJB clients to call business methods.
The home interface is used by EJB factory to create and remove search EJB instances
76、bean The life cycle of an instance
For Stateless Session Beans, Entity Beans, and Message Driven Beans, there is generally buffer pool management, while for Entity Beans and Statefull Session Beans, there is cache management, which usually includes creating instances, setting context, creating EJB Object (create), business method calls, remove and other processes. For beans with buffer pool management, the instance is not cleared from memory after creating, but the buffer pool scheduling mechanism is used to continuously reuse instances. For beans with cache management, the state of the bean is maintained through activation and deactivation mechanisms and the number of instances in memory is limited.
77、EJBActivation mechanism
Take the Stateful Session Bean as an example: its cache size determines the number of bean instances that can exist simultaneously in memory. According to the MRU or NRU algorithm, the instances are migrated between activation and deactivation states. The activation mechanism is when the client calls a certain EJB instance business method, if the corresponding EJB Object finds that it does not bind the corresponding bean instance, it will reply (activate) this instance from its deactivated bean storage (storing the instance through the serialization mechanism). The corresponding ejbActive and ejbPassivate methods will be called before the state changes.
78、EJBSeveral types of
Session Bean, Entity Bean Message Driven Bean
Session beans can be divided into stateful and stateless
Entity beans can be divided into two types: bean management continuity (BMP) and container management continuity (CMP).
79, customer service callEJBSeveral basic steps for an object
Set the JNDI service factory and JNDI service address system properties, find the Home interface, call the Create method from the Home interface to create the Remote interface, and call its business methods through the Remote interface.
80, how to giveweblogicSpecify the size of memory?
In the script to start Weblogic (startServerName in the corresponding server directory of Domian), add set MEM_ARGS=-Xms32m -Xmx200m, and the minimum memory can be adjusted to 32M and the maximum 200M
81, how to set itweblogicHot-start mode(Development Model)With product release mode?
You can modify the startup mode of the corresponding server to one of the development or product modes in the management console. Or modify the service startup file or commenv file and add set PRODUCTION_MODE=true.
82, no need to enter the username and password when starting?
Modify the service startup file and add WLS_USER and WLS_PW items. You can also add encrypted username and password to the file.
83,existweblogicManagement Taichung for an application domain(Or a website,Domain)conductjmsandejbAfter configuring related information such as connection pool,What file is actually saved in?
Saved in this Domain file, it is the core configuration file of the server.
84, talkweblogicOneDomainThe default directory structure?For example, to make a simple oneIn which directory,You can enter it in the browser
http://host:port number// to see the running results? For example, I used one of them written by myselfjavaBeanWhat to do?
Domain directory server directory applications. Putting the application directory in this directory will be accessible as an application. If it is a web application, the application directory needs to meet the requirements of the web application directory. The jsp file can be placed directly in the application directory. Javabean needs to be placed in the classes directory of the WEB-INF directory of the application directory. Setting the default application of the server will be able to achieve no need to enter the application name on the browser.
85,existweblogicRelease inejbWhat configuration files should be involved
Different types of EJBs involve different configuration files, and all the configuration files involved include, and entity beans generally require
86, how toweblogicConducted insslConfiguration and client authentication configuration or talk aboutj2ee(standard)conductsslConfiguration
Default installation and KeyStore implement SSL, you need to configure the server to use Enable SSL, configure its port, and in product mode, you need to obtain the private key and digital certificate from the CA, create identity and trust keystore, and load the obtained key and digital certificate. It is possible to configure whether this SSL connection is one-way or two-way.
87, how to viewweblogicAlready published inEJB?
You can use the Admin Console to view all published EJBs in its Deployment
88、CORBAWhat is it?What is the purpose?
The CORBA standard is a common Object Request Broker Architecture, which is standardized by an Object Management Group (abbreviated as OMG). Its composition is interface definition language (IDL), language binding (binding: also translated as binder), and protocols that allow interoperability between applications. Its purpose is to write in different programming languages to run in different processes and develop for different operating systems.
89, tell me what you are familiar with or have heard ofj2eeSeveral common modes in?Some views on design patterns
Session Facade Pattern: Use SessionBean to access EntityBean
Message Facade Pattern: Implement asynchronous calls
EJB Command Pattern: Use Command JavaBeans to replace SessionBean for lightweight access
Data Transfer Object Factory: Simplify EntityBean data provisioning features through DTO Factory
Generic Attribute Access: Simplify the features of EntityBean data delivery through the AttibuteAccess interface
Business Interface: Implement the same interface specification business logic consistency through remote (local) interface and Bean class
The design of EJB architecture will directly affect the system's performance, scalability, maintainability, component reusability and development efficiency. The more complex the project is, the larger the project team, the more the importance of good design can be reflected.
90, talk about itweblogicChina Development NewsBeanAt the same timepersistentandnon-persistenThe difference
The persistent MDB can ensure the reliability of message delivery, that is, if there is a problem with the EJB container and the JMS server will still send the message when this MDB is available, and the non-persistent message will be discarded.
Since there is no standard answer, please make some corrections based on what you know
91、ServletWhat methods are generally implemented during execution?
public void init(ServletConfig config)
public ServletConfig getServletConfig()
public String getServletInfo()
public void service(ServletRequest request,ServletResponse response)
public void destroy()
The init () method is executed only once during the life cycle of the servlet and is executed when the server loads the servlet. The default init() method usually meets the requirements, but it can also be override as needed, such as managing server-side resources, loading GIF images at one time, initializing database connections, etc. The default inti() method sets the initialization parameters of the servlet and uses its ServltConfig object parameters to start the configuration. Therefore, when overwriting the init() method, you should call () to ensure that these tasks are still executed.
The service () method is the core of the servlet. Before calling the service () method, you should ensure that the init() method has been completed. For HttpServlet, whenever a client requests an HttpServlet object, the service() method of the object must be called. The service function of the default service() method of HttpServlet is to call do functions, doPost() and doGet() corresponding to the HTTP requested method. Therefore, for HttpServlet, the doPost() and doGet() methods are generally overridden.
The destroy() method is only executed once during the life cycle of the servlet, that is, it is executed when the server stops uninstalling the servlet, and closes the servlet as part of the server process. The default destroy() method usually meets the requirements, but it can also be override, such as saving statistics in a file when uninstalling the servlet, or closing the database connection.
The getServletConfig() method returns a servletConfig object, which is used to return the initialization parameters and servletContext. The servletContext interface provides environment information about the servlet.
The getServletInfo() method provides information about the servlet, such as the author, version, copyright.
92、j2eeCommonly used design patterns? Explain the factory model.
23 design patterns in Java:
Factory (factory mode), Builder (built mode), Factory Method (factory method mode),
Prototype (original model mode), Singleton (singleton mode), Facade (facade mode),
Adapter (adapter mode), Bridge (bridge mode), Composite (composition mode),
Decorator, Flyweight, Proxy,
Command, Interpreter, Visitor,
Iterator (iterative sub-mode), Mediator (mediator mode), Memento (memorandum mode),
Observer, State, Strategy,
Template Method, Chain Of Responsibleity
Factory pattern: Factory pattern is a pattern that is often used. Classes implemented according to factory pattern can generate instances of a certain class in a set of classes based on the provided data. Usually, this set of classes has a common abstract parent class and implements the same method, but these methods perform different operations on different data. First, you need to define a base class, and the subclass of this class implements the methods in the base class through different methods. Then you need to define a factory class, which can generate different subclass instances according to the conditions. After obtaining an instance of a subclass, the developer can call the methods in the base class without considering which subclass instance is returned.
93、EJBIts business interface needs to be directly implemented orHomeInterface, please briefly explain the reasons.
Remote interfaces and Home interfaces do not need to be implemented directly. Their implementation code is generated by the server. The corresponding implementation class during the program will be used as an instance of the corresponding interface type.
In fact, I have never understood how EJB's remote interface, home interface, and bean classes are used. Maybe I should further understand the principles of EJB. I found an original article, so let's talk about the principles of EJB call. In fact, what we need to understand most on this issue is the principle of the RMI mechanism.
A remote object must include at least 4 class files: remote object, remote object interface, object stub that implements remote interface, and object skeleton.
In EJB, at least 10 classes must be included:
Bean class, bean implementation class for specific App Server
The remote interface of Bean, the remote interface implementation class of a specific App Server, the stub class and the skeleton class of the remote interface implementation class of a specific App Server.
Bean's home interface, home interface implementation class for specific App Server, stub class and skeleton class for specific App Server's home interface implementation class.
Unlike RMI, there are only 3 that users really need to write in these 10 classes in EJB, namely, remote interface, home interface, how to generate the other 7, where they are packaged, whether more class files are needed, and whether there are big differences according to different App Servers.
Weblogic:
The stub class and skeleton class of the weblogic implementation class of the home interface and remote interface are dynamically generated by weblogic bytecodes of the stub class and skeleton class when EJB is deployed to weblogic, so these 4 class files cannot be seen.
For a remote call to EJB by client, multiple RMI loops of two remote objects must be passed. First, look up the Home interface through JNDI and obtain the Home interface implementation class. This process is actually quite complicated. First, find the Weblogic implementation class of the Home interface, and then create an object instance of the stub class of the Weblogic implementation class of the Home interface, and serialize it to the client (note that the instance of the stub class is dynamically sent to the client by the server in the first RMI loop, so the client does not need to save the stub class of the Weblogic implementation class of the Home interface). Finally, the client obtains the object instance of the stub class (ordinary RMI needs to save the stub class on the client, but EJB does not need it because the server will send the object instance of the stub class to the client).
After the client gets the stub class object instance of the Weblogic implementation class of the Home interface to the server, it calls the create method of the stub class (in the code, it is (), but the background needs to do a lot of things). So after the second RMI loop, on the server side, the skeleton class of the Weblogic implementation class of the Home interface receives the call information of the stub class, it then calls the create method of the Weblogic implementation class of the Home interface.
On the server side, the create method of the Weblogic implementation class of the Home interface calls the ejbCreate method of the Weblogic implementation class of the Bean class, create or allocate an EJB instance on the server side, and then serialize the stub class object instance of the Weblogic implementation class of the remote interface of the EJB instance to send to the client.
The client receives an object instance of the stub class of the remote interface of the remote interface, and calls the method of the object instance (in the client code, it is actually a call to the remote interface), which will be transmitted to the skeleton class object of the remote interface of the server, and the skeleton class object then calls the Weblogic implementation class of the corresponding remote interface, and then the Weblogic implementation class of the remote interface will then call the Weblogic implementation class of the Bean class, so that the remote call of the EJB object is completed.
Let’s take ordinary RMI as an example. There are 4 classes, namely the remote object, the object’s interface, the object’s stub class and the skeleton class. The object itself and the object's stub class implement the interface class at the same time. When we call remote objects on the client code, although we manipulate the interface in the code, we are essentially manipulating the stub class, for example:
Interface class: Hello
Remote object: Hello_Server
stub class: Hello_Stub
skeleton class: Hello_Skeleton
The client code should be written like this:
Hello h = new Hello_Stub();
();
We won't write these:
Hello_Stub h = new Hello_Stub();
();
Because the use of interfaces is more applicable, even if the interface implementation class is replaced, there is no need to change the code. Therefore, the client needs two files and Hello_Stub.class. But for EJB, Hello_Stub.class is not needed because the server will send it, but the file client cannot save it and must have it. On the surface, our client code is manipulating Hello, but don't forget that Hello is just an interface, abstract, and essentially manipulating Hello_Stub.
Take EJB on Weblogic as an example. The 10 classes are:
Bean class: HelloBean (written by user)
Weblogic implementation class of Bean class: HelloBean_Impl (generated by EJBC)
Home interface: HelloHome (written by user)
Weblogic implementation class HelloBean_HomeImpl (EJBC generation)
The stub class of the Weblogic implementation class of the Home interface HelloBean_HomeImpl_WLStub (dynamic generation of bytecode during deployment)
The Weblogic implementation class of the Home interface HelloBean_HomeImpl_WLSkeleton (dynamic generation of bytecode during deployment)
Remote interface: Hello (user written)
Weblogic implementation class HelloBean_EOImpl (EJBC generation) of Remote interface
The stub class of the Weblogic implementation class of the Remote interface HelloBean_EOImpl_WLStub (dynamic generation of bytecode during deployment)
Remote interface Weblogic implementation class skeleton class HelloBean_EOImpl_WLSkeleton (dynamic generation of bytecode during deployment)
The client only needs these two files.
HelloHome home = (Home) (("Hello"), );
This line of code is to get the Home interface from JNDI, but please remember! The interface is abstract, so what kind of object instance is the home object? It's very simple. You can see it by looking at it by looking at it. The following line is the output result:
HelloBean_HomeImpl_WLStub@18c458
This indicates that home, the object obtained by looking up from the server's JNDI tree, is actually an instance of the HelloBean_HomeImpl_WLStub class.
Next client code:
Hello h = ()
Similarly, Hello is just an abstract interface, so what is the h object? Print it:
HelloBean_EOImpl_WLStub@8fa0d1
It turns out to be an object instance of HelloBean_EOImpl_WLStub.
Use this example to briefly describe the EJB calling process:
First, the client JNDI query. The object bound to the name Hello on the server JNDI tree is actually HelloBean_HomeImpl_WLStub, so the server will create an object instance of HelloBean_HomeImpl_WLStub and serialize it to return it to the client.
So the client gets the home object, which on the surface is an instance of the HelloHome interface, but in fact, a remote call is made to get the object instance of the HelloBean_HomeImpl_WLStub class. Don't forget that HelloBean_HomeImpl_WLStub also implements the HelloHome interface.
Then () is essentially HelloBean_HomeImpl_WLStub.create(), which sends information to HelloBean_HomeImpl_WLSkeleton. After HelloBean_HomeImpl_WLSkeleton receives the information, it calls HelloBean_HomeImpl's create method, and then completes the first complete RMI loop.
Note that during this RMI loop, the remote object is HelloBean_HomeImpl, the interface of the remote object is HelloHome, the stub of the object is HelloBean_HomeImpl_WLStub, and the skeleton of the object is HelloBean_HomeImpl_WLSkeleton.
Then HelloBean_HomeImpl calls the HelloBean_Impl's ejbCreate method, and the HelloBean_Impl's ejbCreate method will be responsible for creating or allocating a Bean instance and creating a HelloBean_EOImpl_WLStub object instance.
What's more interesting in this step is that in the previous RMI loop, the remote object HelloBean_HomeImpl has a proxy class HelloBean_HomeImpl_WLStub on the client, but in this step, HelloBean_HomeImpl itself acts as the proxy class of HelloBean_Impl. However, HelloBean_HomeImpl is not on the client, but on the server, so it does not perform RMI.
Then the object instance of HelloBean_EOImpl_WLStub is serialized and returned to the client. This step is also very interesting. In the last RMI process, the protagonists were HelloBean_HomeImpl and its proxy class HelloBean_HomeImpl_WLStub, but this time it was replaced by HelloBean_EOImpl and its proxy class HelloBean_EOImpl_WLStub to play.
Hello h = ();();
Assuming that the Hello interface has a helloWorld remote method, on the surface, it is calling the helloWorld method of the Hello interface, but it is actually calling the helloWorld method of HelloBean_EOImpl_WLStub.
Then the helloWorld method of HelloBean_EOImpl_WLStub will send information to HelloBean_EOImpl_WLSkeleton on the server. After HelloBean_EOImpl_WLSkeleton receives the information, it will call HelloBean_EOImpl's helloWorld method. At this point, the second complete RMI cycle process is completed.
Just now, HelloBean_EOImpl was called as a remote object. Its proxy class is HelloBean_EOImpl_WLStub, but now HelloBean_EOImpl is to be the proxy class of HelloBean_Impl. Now HelloBean_EOImpl calls HelloBean_Impl's helloWorld method. Notice! HelloBean_Impl inherits HelloBean, and the helloWorld method in HelloBean is the code we wrote ourselves, and now we have finally called the code we wrote!
At this point, an EJB call process has finally been completed. During the entire process, the main classes that the server needs to call are HelloBean_Impl, HelloBean_HomeImpl, HelloBean_HomeImpl_WLSkeleton, HelloBean_EOImpl, HelloBean_EOImpl_WLSkeleton. The main classes called by the client are HelloBean_HomeImpl_WLStub and HelloBean_EOImpl_WLStub. These two classes will not appear directly in the client code. The classes that appear in the code are their interfaces HelloHome and Hello, so the client needs these two interface files, and Stub is transmitted to them by the server.
/nobo123/image/27229257
/?t=3832&postdays=0&postorder=asc&start=0
94, What are the methods of sorting? Please list it. useJAVAImplement a quick sort.
The sorting methods include: insert sort (direct insert sort, Hill sort), exchange sort (bubble sort, quick sort), select sort (directly select sort, heap sort), merge sort, allocate sort (box sort, cardinal sort)
Quick sort pseudocode.
//Sort a[0:n-1] using the quick sort method
Select an element from a[0:n-1] as m i d d l e, which is the fulcrum
Divide the remaining elements into two segments left and r i g h t so that the elements in l e f t are less than or equal to the fulcrum, while the elements in right are greater than or equal to the fulcrum.
Recursively sort left using quick sort method
Recursively sort right using quick sort method
The result is l e f t + m i d d l e + r i g h t
95, please refer to the followingJ2EECommonly used nouns for explanation(Or a brief description)
web container: provides an environment for the application components (JSP, SERVLET) in it, so that JSP, SERVLET directly connects the environment variables in the container, and does not need to pay attention to other system issues. Mainly WEB server is used to implement it. For example: TOMCAT, WEBLOGIC, WEBSPHERE, etc. The interfaces provided by this container strictly comply with the WEB APPLICATION standard in the J2EE specification. We call WEB servers that comply with the above standards the WEB container in J2EE.
Web container: A container that implements the Web component protocol in the J2EE architecture. This protocol specifies a web component runtime environment, including security, consistency, lifecycle management, transactions, configuration and other services. A container that provides the same services as the JSP and J2EE platform APIs interfaces. A Web container is provided by a web server or a J2EE server.
EJB container: Enterprise java bean container. It has more industry characteristics. It provides various management functions for EJB to run components in it. As long as the EJB that meets the J2EE specification is placed in the container, it will be managed efficiently by the container immediately. And system-level services can be obtained through ready-made interfaces. For example, email service and transaction management.
A container that implements the EJB component specification in the J2EE architecture.
This specification specifies the runtime environment of an Enterprise bean, including security, consistency, life cycle, transaction,
Configuration, and other services.
JNDI: (Java Naming & Directory Interface) JAVA named directory service. The main functions are: providing a directory system that allows applications from other places to leave their own indexes on them, so as to meet the functions of quickly finding and positioning distributed applications.
JMS: (Java Message Service) JAVA messaging service. Mainly realizes communication between various applications. Includes peer-to-peer and broadcast.
JTA: (Java Transaction API) JAVA transaction service. Provides various distributed transaction services. The application simply needs to call the interface it provides.
JAF: (Java Action FrameWork) JAVA security authentication framework. Provides some frameworks for security control. Let developers implement their own personalized security control policies through various deployments and customizations.
RMI/IIOP: (Remote Method Invocation/internet object request intermediary protocol) They are mainly used for