A collection of basic Java interview questions and answers (122 basic questions and 19 code questions), the specific details are as follows:
1. What are the aspects of object-oriented characteristics
1. Abstract:
Abstraction is to ignore aspects of a topic that are not related to the current goal in order to pay more attention to aspects related to the current goal. Abstract does not intend to understand all the problems, but only choose some of them, without some details for the time being. Abstraction includes two aspects: one is process abstraction and the other is data abstraction.
2. Inheritance:
Inheritance is a hierarchical model that connects classes and allows and encourages reuse of classes. It provides a way to clearly express commonality. A new class of an object can be derived from an existing class, and this process is called class inheritance. The new class inherits the characteristics of the original class. The new class is called the derived class (subclass) of the original class, while the original class is called the base class (parent class) of the new class. A derived class can inherit methods and instance variables from its base class, and the class can modify or add new methods to make it more suitable for special needs.
3. Packaging:
Encapsulation is to enclose the process and data, and access to the data can only be achieved through the defined interface. Object-oriented computing begins with this basic concept that the real world can be portrayed as a series of fully autonomous, encapsulated objects that access other objects through a protected interface.
4. Polymorphism:
Polymorphism refers to allowing objects of different classes to respond to the same message. Polymorphisms include parameterized polymorphisms and inclusion polymorphisms. Polymorphic languages have the advantages of flexibility, abstraction, behavior sharing, and code sharing, which solves the problem of the same name of application functions.
2. Is String the most basic data type?
Basic data types include byte, int, char, long, float, double, boolean, and short.
The java.lang.String class is 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
shortShortShort
intInteger
longLong
floatFloat
doubleDouble
Reference types and primitive types behave completely differently, 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, i.e. character data containing multiple characters. This String class provides strings that are numerical invariant. 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 indexing 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 implement storage. Indexing data by sequence number requires forward or backward traversal, but when inserting data, only the front and back items of this item need to be 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 does 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 (if it is ArrayList: List lst = Collections.synchronizedList(new ArrayList()); if it is HashMap: Map map = Collections.synchronizedMap(new HashMap());).
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 the return value?
Overriding and overloading of methods are different manifestations of Java polymorphism. Overriding is a manifestation of polymorphism between parent and child class, while 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. To it, the definition in the parent class is as if it is "blocked". If multiple methods of the same name are defined in a class, they have different parameters or different parameter types, they are 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, 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 Webspere,
In containers like 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 with jsp:include action <jsp:include page="included.jsp" flush="true" />It always checks for changes in the included file, is suitable for including dynamic pages, and can take parameters.
Static INCLUDE is implemented with include pseudo-code, and it will not check the changes in the included files. It is suitable for static pages <%@ include file="included.htm" %>
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 does it need GC?
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 is wrong? short s1 = 1; s1 += 1; What is 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. How much does Math.round(11.5) equal? How much does Math.round(-11.5) equal?
Math.round(11.5)==12
Math.round(-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"); How many String Objects have been created?
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=tt.new Inc();Dec dec=tt.new Dec();for(int i=0;i<2;i++){Thread t=new Thread(inc);t.start();t=new Thread(dec);t.start();}}private synchronized void inc(){j++;System.out.println(Thread.currentThread().getName()+"-inc:"+j);}private synchronized void dec(){j--;System.out.println(Thread.currentThread().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++){inc();}}}class Dec implements Runnable{public void run(){for(int i=0;i<100;i++){dec();}}}}}}29. Is there a goto in Java?
The reserved words in java are not used in java now.
30. Should I use run() or start() to start a thread?
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 makes a request to establish an instance of a bean, the EJB container does not necessarily create a new instance of a 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, DOMEXException, EmptyStackException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, 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 implements an interface? Can an abstract class inherit from a 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. Does List, Set, Map inherit from the Collection interface?
List, Set is, Map is not
36. What is the working mechanism of data connection pooling?
When the J2EE server starts, a certain number of pool connections will be established and no less than this number of pool connections will be maintained. 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 be synchronized at the same time?
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 be override?
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. Can swtich act on byte , long, and 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 {} . 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 question: Use the most efficient method to calculate what is the equivalent of 2 times 8?
2 << 3
45. Two objects have the same value (x.equals(y) == true), but they can have different hash codes. Is this right?
No, there is the same hash code.
46. When an object is passed to a method as a parameter , this method can change the properties of the object and return the changed result. So is it a value pass or a reference pass 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 yourself an instance 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 directly access 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 compared to the above. It does not require the object to be generated every time, but the first time // generates instances when used, which improves 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 compared to 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 exceptions with the throw keyword. All exceptions are subclasses of java.lang.Thowable.
51. Advantages and principles of garbage recycling. And consider two recycling mechanisms.
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 me 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 the principle and mechanism of JVM loading class files?
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. Can a Chinese character be stored in a char-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. How many implementation methods are there for multithreading, what are they? How many implementation methods are there for 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. Built-in objects and methods of JSP.
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 responses sent back to the browser (such as cookies, header information, etc.)
The out object is an instance of javax.jsp.JspWriter and provides several methods that you can use to return output results to the browser.
pageContext represents a javax.servlet.jsp.PageContext 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 javax.servlet.http.HttpSession object. Session can store user status information
applicaton represents a javax.servle.ServletContext object. This helps find information about the servlet engine and servlet environment
config represents a javax.servlet.ServletConfig object. This object is used to access the initialization parameters of the servlet instance.
Page represents a servlet instance generated from the page
58. The basic concept of threads, the basic state of threads and the relationship 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. Common JSP instructions
<%@page language=”java” contextType=”text/html;charset=gb2312” session=”true” buffer=”64kb” autoFlush=”true” isThreadSafe=”true” info=”text” errorPage=”error.jsp” isErrorPage=”true” isELIgnored=”true” isELIgnored=”true” pageEncoding=”gb2312” import=”java.sql.*”%>isErrorPage(whether the Exception object can be used), isELIgnored(whether the expression is ignored)<%@include file=”filename”%>%@taglib prefix=”c”uri=”http://…”%
60. Under what circumstances do doGet() and doPost() are called?
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. The life cycle of servlet
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 realistically use a single-threaded servlet mode
<%@ page isThreadSafe=”false”%>
63. Methods of object transfer between pages
Request, session, application, cookie, etc.
64. What are the similarities and differences between JSP and Servlets, 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 actions). 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 attribute that represents a user experience for a certain Web client. A web session can and often spans multiple client requests
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. The main methods of the Request 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():返回request对象所有属性的名字集合,结果是一个枚举的实例
getCookies():返回客户端的所有Cookie对象,结果是一个Cookie数组
getCharacterEncoding():返回请求中的字符编码方式
getContentLength():返回请求的Body的长度
getHeader(String name):获得HTTP协议定义的文件头信息
getHeaders(String name):返回指定名字的request Header的所有值,结果是一个枚举的实例
getHeaderNames():返回所以request Header的名字,结果是一个枚举的实例
getInputStream():返回请求的输入流,用于获得请求中的数据
getMethod():获得客户端向服务器端传送数据的方法
getParameter(String name):获得客户端传送给服务器端的有name指定的参数值
getParameterNames():获得客户端传送给服务器端的所有参数的名字,结果是一个枚举的实例
getParameterValues(String name):获得有name指定的参数的所有值
getProtocol():获取客户端向服务器端传送数据所依据的协议名称
getQueryString():获得查询字符串
getRequestURI():获取发出请求字符串的客户端地址
getRemoteAddr():获取客户端的IP地址
getRemoteHost():获取客户端的名字
getSession([Boolean create]):返回和请求相关Session
getServerName():获取服务器的名字
getServletPath():获取客户端所请求的脚本文件的路径
getServerPort():获取服务器的端口号
removeAttribute(String name):删除请求中的一个属性
67、J2EE是技术还是平台还是框架?
J2EE本身是一个标准,一个为企业分布式应用的开发提供的标准平台。
J2EE也是一个框架,包括JDBC、JNDI、RMI、JMS、EJB、JTA等技术。
68、我们在web应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串?
Public String translate (String str) {String tempStr = "";try {tempStr = new String(str.getBytes("ISO-8859-1"), "GBK");tempStr = tempStr.trim();}catch (Exception e) {System.err.println(e.getMessage());}return tempStr;}69、简述逻辑操作(&,|,^)与条件操作(&&,||)的区别。
区别主要答两点:
a.条件操作只能操作布尔型的,而逻辑操作不仅可以操作布尔型,而且可以操作数值型
b.逻辑操作不会产生短路
70、XML文档定义有几种形式?它们之间有何本质区别?解析XML文档有哪几种方式?
a: 两种形式dtd schema,
b: 本质区别:schema本身是xml的,可以被XML解析器解析(这也是从DTD上发展schema的根本目的),
c:有DOM,SAX,STAX等
DOM:处理大型文件时其性能下降的非常厉害。这个问题是由DOM的树结构所造成的,这种结构占用的内存较多,而且DOM必须在解析文件之前把整个文档装入内存,适合对XML的随机访问
SAX:不现于DOM,SAX是事件驱动型的XML解析方式。它顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,它会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问
STAX:Streaming API for XML (StAX)
71、简述synchronized和java.util.concurrent.locks.Lock的异同?
主要相同点:Lock能完成synchronized所实现的所有功能
主要不同点:Lock有比synchronized更精确的线程语义和更好的性能。synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。
72、EJB的角色和三个对象
一个完整的基于EJB的分布式计算结构由六个角色组成,这六个角色可以由不同的开发商提供,每个角色所作的工作必须遵循Sun公司提供的EJB规范,以保证彼此之间的兼容性。这六个角色分别是EJB组件开发者(Enterprise Bean Provider) 、应用组合者(Application Assembler)、部署者(Deployer)、EJB 服务器提供者(EJB Server Provider)、EJB 容器提供者(EJB Container Provider)、系统管理员(System Administrator)
三个对象是Remote(Local)接口、Home(LocalHome)接口,Bean类
73、EJB容器提供的服务
主要提供声明周期管理、代码产生、持续性管理、安全、事务管理、锁和并发行管理等服务。
74、EJB规范规定EJB中禁止的操作有哪些?
1.不能操作线程和线程API(线程API指非线程对象的方法如notify,wait等),2.不能操作awt,3.不能实现服务器功能,4.不能对静态属生存取,5.不能使用IO操作直接存取文件系统,6.不能加载本地库.,7.不能将this作为变量和返回,8.不能循环调用。
75、remote接口和home接口主要作用
remote接口定义了业务方法,用于EJB客户端调用业务方法。
home接口是EJB工厂用于创建和移除查找EJB实例
76、bean 实例的生命周期
对于Stateless Session Bean、Entity Bean、Message Driven Bean一般存在缓冲池管理,而对于Entity Bean和Statefull Session Bean存在Cache管理,通常包含创建实例,设置上下文、创建EJB Object(create)、业务方法调用、remove等过程,对于存在缓冲池管理的Bean,在create之后实例并不从内存清除,而是采用缓冲池调度机制不断重用实例,而对于存在Cache管理的Bean则通过激活和去激活机制保持Bean的状态并限制内存中实例数量。
77、EJB的激活机制
以Stateful Session Bean 为例:其Cache大小决定了内存中可以同时存在的Bean实例的数量,根据MRU或NRU算法,实例在激活和去激活状态之间迁移,激活机制是当客户端调用某个EJB实例业务方法时,如果对应EJB Object发现自己没有绑定对应的Bean实例则从其去激活Bean存储中(通过序列化机制存储实例)回复(激活)此实例。状态变迁前会调用对应的ejbActive和ejbPassivate方法。
78、EJB的几种类型
会话(Session)Bean ,实体(Entity)Bean 消息驱动的(Message Driven)Bean
会话Bean又可分为有状态(Stateful)和无状态(Stateless)两种实体Bean可分为Bean管理的持续性(BMP)和容器管理的持续性(CMP)两种
79、客服端调用EJB对象的几个基本步骤
设置JNDI服务工厂以及JNDI服务地址系统属性,查找Home接口,从Home接口调用Create方法创建Remote接口,通过Remote接口调用其业务方法。
80、如何给weblogic指定大小的内存?
在启动Weblogic的脚本中(位于所在Domian对应服务器目录下的startServerName),增加set MEM_ARGS=-Xms32m -Xmx200m,可以调整最小内存为32M,最大200M
81、如何设定的weblogic的热启动模式(开发模式)与产品发布模式?
可以在管理控制台中修改对应服务器的启动模式为开发或产品模式之一。或者修改服务的启动文件或者commenv文件,增加set PRODUCTION_MODE=true。
82、如何启动时不需输入用户名与密码?
修改服务启动文件,增加WLS_USER和WLS_PW项。也可以在boot.properties文件中增加加密过的用户名和密码.
83、在weblogic管理制台中对一个应用域(或者说是一个网站,Domain)进行jms及ejb或连接池等相关信息进行配置后,实际保存在什么文件中?
保存在此Domain的config.xml文件中,它是服务器的核心配置文件。
84、说说weblogic中一个Domain的缺省目录结构?比如要将一个简单的helloWorld.jsp放入何目录下,然的在浏览器上就可打入http://主机:端口号//helloword.jsp就可以看到运行结果了? 又比如这其中用到了一个自己写的javaBean该如何办?
Domain目录服务器目录applications,将应用目录放在此目录下将可以作为应用访问,如果是Web应用,应用目录需要满足Web应用目录要求,jsp文件可以直接放在应用目录中,Javabean需要放在应用目录的WEB-INF目录的classes目录中,设置服务器的缺省应用将可以实现在浏览器上无需输入应用名。
85、在weblogic中发布ejb需涉及到哪些配置文件
不同类型的EJB涉及的配置文件不同,都涉及到的配置文件包括ejb-jar.xml,weblogic-ejb-jar.xmlCMP实体Bean一般还需要weblogic-cmp-rdbms-jar.xml
86、如何在weblogic中进行ssl配置与客户端的认证配置或说说j2ee(标准)进行ssl的配置
缺省安装中使用DemoIdentity.jks和DemoTrust.jks KeyStore实现SSL,需要配置服务器使用Enable SSL,配置其端口,在产品模式下需要从CA获取私有密钥和数字证书,创建identity和trust keystore,装载获得的密钥和数字证书。可以配置此SSL连接是单向还是双向的。
87、如何查看在weblogic中已经发布的EJB?
可以使用管理控制台,在它的Deployment中可以查看所有已发布的EJB
88、CORBA是什么?用途是什么?
CORBA 标准是公共对象请求代理结构(Common Object Request Broker Architecture),由对象管理组织(Object Management Group,缩写为OMG)标准化。它的组成是接口定义语言(IDL), 语言绑定(binding:也译为联编)和允许应用程序间互操作的协议。 其目的为:用不同的程序设计语言书写在不同的进程中运行,为不同的操作系统开发。
89、说说你所熟悉或听说过的j2ee中的几种常用模式?及对设计模式的一些看法
Session Facade Pattern:使用SessionBean访问EntityBean
Message Facade Pattern:实现异步调用
EJB Command Pattern:使用Command JavaBeans取代SessionBean,实现轻量级访问
Data Transfer Object Factory:通过DTO Factory简化EntityBean数据提供特性
Generic Attribute Access:通过AttibuteAccess接口简化EntityBean数据提供特性
Business Interface:通过远程(本地)接口和Bean类实现相同接口规范业务逻辑一致性EJB架构的设计好坏将直接影响系统的性能、可扩展性、可维护性、组件可重用性及开发效率。项目越复杂,项目队伍越庞大则越能体现良好设计的重要性。
90、说说在weblogic中开发消息Bean时的persistent与non-persisten的差别
persistent方式的MDB可以保证消息传递的可靠性,也就是如果EJB容器出现问题而JMS服务器依然会将消息在此MDB可用的时候发送过来,而non-persistent方式的消息将被丢弃。
91、Servlet执行时一般实现哪几个方法?
public void init(ServletConfig config)public ServletConfig getServletConfig()public String getServletInfo()public void service(ServletRequest request,ServletResponse response)public void destroy()
92、j2ee常用的设计模式?说明工厂模式。
Java中的23种设计模式:
Factory(工厂模式), Builder(建造模式), Factory Method(工厂方法模式),
Prototype(原始模型模式),Singleton(单例模式), Facade(门面模式),
Adapter(适配器模式), Bridge(桥梁模式), Composite(合成模式),
Decorator(装饰模式), Flyweight(享元模式), Proxy(代理模式),
Command(命令模式), Interpreter(解释器模式), Visitor(访问者模式),
Iterator(迭代子模式), Mediator(调停者模式), Memento(备忘录模式),
Observer(观察者模式), State(状态模式), Strategy(策略模式),
Template Method(模板方法模式), Chain Of Responsibleity(责任链模式)
工厂模式:工厂模式是一种经常被使用到的模式,根据工厂模式实现的类可以根据提供的数据生成一组类中某一个类的实例,通常这一组类有一个公共的抽象父类并且实现了相同的方法,但是这些方法针对不同的数据进行了不同的操作。首先需要定义一个基类,该类的子类通过不同的方法实现了基类中的方法。然后需要定义一个工厂类,工厂类可以根据条件生成不同的子类实例。当得到子类的实例后,开发人员可以调用基类中的方法而不必考虑到底返回的是哪一个子类的实例。
93、EJB需直接实现它的业务接口或Home接口吗,请简述理由。
远程接口和Home接口不需要直接实现,他们的实现代码是由服务器产生的,程序运行中对应实现类会作为对应接口类型的实例被使用。
94、排序都有哪几种方法?请列举。用JAVA实现一个快速排序。
排序的方法有:插入排序(直接插入排序、希尔排序),交换排序(冒泡排序、快速排序),选择排序(直接选择排序、堆排序),归并排序,分配排序(箱排序、基数排序)
快速排序的伪代码。
/ /使用快速排序方法对a[ 0 :n- 1 ]排序从a[ 0 :n- 1 ]中选择一个元素作为middle,该元素为支点把余下的元素分割为两段left 和right,使得left中的元素都小于等于支点,而right 中的元素都大于等于支点递归地使用快速排序方法对left 进行排序递归地使用快速排序方法对right 进行排序所得结果为left + middle + right
95、请对以下在J2EE中常用的名词进行解释(或简单描述)
web容器:给处于其中的应用程序组件(JSP,SERVLET)提供一个环境,使JSP,SERVLET直接更容器中的环境变量接口交互,不必关注其它系统问题。主要有WEB服务器来实现。例如:TOMCAT,WEBLOGIC,WEBSPHERE等。该容器提供的接口严格遵守J2EE规范中的WEB APPLICATION 标准。我们把遵守以上标准的WEB服务器就叫做J2EE中的WEB容器。
EJB容器:Enterprise java bean 容器。更具有行业领域特色。他提供给运行在其中的组件EJB各种管理功能。只要满足J2EE规范的EJB放入该容器,马上就会被容器进行高效率的管理。并且可以通过现成的接口来获得系统级别的服务。例如邮件服务、事务管理。
JNDI:(Java Naming & Directory Interface)JAVA命名目录服务。主要提供的功能是:提供一个目录系统,让其它各地的应用程序在其上面留下自己的索引,从而满足快速查找和定位分布式应用程序的功能。
JMS:(Java Message Service)JAVA消息服务。主要实现各个应用程序之间的通讯。包括点对点和广播。
JTA:(Java Transaction API)JAVA事务服务。提供各种分布式事务服务。应用程序只需调用其提供的接口即可。
JAF:(Java Action FrameWork)JAVA安全认证框架。提供一些安全控制方面的框架。让开发者通过各种部署和自定义实现自己的个性安全控制策略。
RMI/IIOP:(Remote Method Invocation /internet对象请求中介协议)他们主要用于通过远程调用服务。例如,远程有一台计算机上运行一个程序,它提供股票分析服务,我们可以在本地计算机上实现对其直接调用。当然这是要通过一定的规范才能在异构的系统之间进行通信。RMI是JAVA特有的。
96、JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗?
Java通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。在Java中,每个异常都是一个对象,它是Throwable类或其它子类的实例。当一个方法出现异常后便抛出一个异常对象,该对象中包含有异常信息,调用这个对象的方法可以捕获到这个异常并进行处理。Java的异常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。一般情况下是用try来执行一段程序,如果出现异常,系统会抛出(throws)一个异常,这时候你可以通过它的类型来捕捉(catch)它,或最后(finally)由缺省处理器来处理。
用try来指定一块预防所有“异常”的程序。紧跟在try程序后面,应包含一个catch子句来指定你想要捕捉的“异常”的类型。
throw语句用来明确地抛出一个“异常”。
throws用来标明一个成员函数可能抛出的各种“异常”。
Finally为确保一段代码不管发生什么“异常”都被执行一段代码。
可以在一个成员函数调用的外面写一个try语句,在这个成员函数内部写另一个try语句保护其他代码。每当遇到一个try语句,“异常”的框架就放到堆栈上面,直到所有的try语句都完成。如果下一级的try语句没有对某种“异常”进行处理,堆栈就会展开,直到遇到有处理这种“异常”的try语句。
97、一个“.java”源文件中是否可以包括多个类(不是内部类)?有什么限制?
Can.必须只有一个类名与文件名相同。
98、MVC的各个部分都有那些技术来实现?如何实现?
MVC是Model-View-Controller的简写。"Model" 代表的是应用的业务逻辑(通过JavaBean,EJB组件实现), "View" 是应用的表示面(由JSP页面产生),"Controller" 是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。
99、java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?
有两种实现方法,分别是继承Thread类与实现Runnable接口
用synchronized关键字修饰同步方法
反对使用stop(),是因为它不安全。它会解除由线程获取的所有锁定,而且如果对象处于一种不连贯状态,那么其他线程能在那种状态下检查和修改它们。结果很难检查出真正的问题所在。suspend()方法容易发生死锁。调用suspend()的时候,目标线程会停下来,但却仍然持有在这之前获得的锁定。此时,其他任何线程都不能访问锁定的资源,除非被“挂起”的线程恢复运行。对任何线程来说,如果它们想恢复目标线程,同时又试图使用任何一个锁定的资源,就会造成死锁。所以不应该使用suspend(),而应在自己的Thread类中置入一个标志,指出线程应该活动还是挂起。若标志指出线程应该挂起,便用wait()命其进入等待状态。若标志指出线程应当恢复,则用一个notify()重新启动线程。
100、java中有几种类型的流? JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?
字节流,字符流。字节流继承于InputStream OutputStream,字符流继承于InputStreamReader OutputStreamWriter。在java.io包中还有许多其他的流,主要是为了提高性能和使用方便。
101、java中会存在内存泄漏吗,请简单描述。
meeting.如:int i,i2; return (i-i2); //when i为足够大的正数,i2为足够大的负数。结果会造成溢位,导致错误。
102、java中实现多态的机制是什么?
方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。
103、垃圾回收器的基本原理是什么?垃圾回收器可以马上回收内存吗?有什么办法主动通知虚拟机进行垃圾回收?
对于GC来说,当程序员创建对象时,GC就开始监控这个对象的地址、大小以及使用情况。通常,GC采用有向图的方式记录和管理堆(heap)中的所有对象。通过这种方式确定哪些对象是"可达的",哪些对象是"不可达的"。当GC确定一些对象为"不可达"时,GC就有责任回收这些内存空间。 Can.程序员可以手动执行System.gc(),通知GC运行,但是Java语言规范并不保证GC一定会执行。
104、静态变量和实例变量的区别?
static i = 10; //常量
class A a; ai =10;//可变
105、什么是java序列化,如何实现java序列化?
序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。
序列化的实现:将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。
106、是否可以从一个static方法内部发出对非static方法的调用?
不可以,如果其中包含对象的method();不能保证对象初始化.
107、写clone()方法时,通常都有一行代码,是什么?
Clone 有缺省行为,super.clone();他负责产生正确大小的空间,并逐位复制。
108、在JAVA中,如何跳出当前的多重嵌套循环?
用break; return 方法。
109、List、Map、Set三个接口,存取元素时,各有什么特点?
List 以特定次序来持有元素,可有重复元素。Set 无法拥有重复元素,内部排序。Map 保存key-value值,value可多值。
110、J2EE是什么?
J2EE是Sun公司提出的多层(multi-diered),分布式(distributed),基于组件(component-base)的企业级应用模型(enterpriese application model).在这样的一个应用系统中,可按照功能划分为不同的组件,这些组件又可在不同计算机上,并且处于相应的层次(tier)中。所属层次包括客户层(clietn tier)组件,web层和组件,Business层和组件,企业信息系统(EIS)层。
111、UML方面
标准建模语言UML。用例图,静态图(包括类图、对象图和包图),行为图,交互图(顺序图,合作图),实现图。
112、说出一些常用的类,包,接口,请各举5个
常用的类:BufferedReader BufferedWriter FileReader FileWirter String Integer
常用的包:java.lang java.awt java.io java.util java.sql
常用的接口:Remote List Map Document NodeList
113、开发中都用到了那些设计模式?用在什么场合?
每个模式都描述了一个在我们的环境中不断出现的问题,然后描述了该问题的解决方案的核心。通过这种方式,你可以无数次地使用那些已有的解决方案,无需在重复相同的工作。主要用到了MVC的设计模式。用来开发JSP/Servlet或者J2EE的相关应用。简单工厂模式等。
114、jsp有哪些动作?作用分别是什么?
JSP共有以下6种基本动作jsp:include:在页面被请求的时候引入一个文件。 jsp:useBean:寻找或者实例化一个JavaBean。 jsp:setProperty:设置JavaBean的属性。 jsp:getProperty:输出某个JavaBean的属性。 jsp:forward:把请求转到一个新的页面。 jsp:plugin:根据浏览器类型为Java插件生成OBJECT或EMBED标记。
115、Anonymous Inner Class (匿名内部类)是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?
可以继承其他类或完成其他接口,在swing编程中常用此方式。
116、应用服务器与WEB SERVER的区别?
应用服务器:Weblogic、Tomcat、Jboss
WEB SERVER:IIS、 Apache
117、BS与CS的联系与区别。
C/S是Client/Server的缩写。服务器通常采用高性能的PC、工作站或小型机,并采用大型数据库系统,如Oracle、Sybase、Informix或SQL Server。客户端需要安装专用的客户端软件。
B/S是Brower/Server的缩写,客户机上只要安装一个浏览器(Browser),如Netscape Navigator或Internet Explorer,服务器安装Oracle、Sybase、Informix或SQL Server等数据库。在这种结构下,用户界面完全通过WWW浏览器实现,一部分事务逻辑在前端实现,但是主要事务逻辑在服务器端实现。浏览器通过Web Server 同数据库进行数据交互。
C/S 与B/S 区别:
1.硬件环境不同:
C/S 一般建立在专用的网络上, 小范围里的网络环境, 局域网之间再通过专门服务器提供连接和数据交换服务.
B/S 建立在广域网之上的, 不必是专门的网络硬件环境,例与电话上网, 租用设备. 信息自己管理. 有比C/S更强的适应范围, 一般只要有操作系统和浏览器就行
2.对安全要求不同
C/S 一般面向相对固定的用户群, 对信息安全的控制能力很强. 一般高度机密的信息系统采用C/S 结构适宜. 可以通过B/S发布部分可公开信息.
B/S 建立在广域网之上, 对安全的控制能力相对弱, 可能面向不可知的用户。
3.对程序架构不同
C/S 程序可以更加注重流程, 可以对权限多层次校验, 对系统运行速度可以较少考虑.
B/S 对安全以及访问速度的多重的考虑, 建立在需要更加优化的基础之上. 比C/S有更高的要求B/S结构的程序架构是发展的趋势, 从MS的.Net系列的BizTalk 2000 Exchange 2000等, 全面支持网络的构件搭建的系统. SUN 和IBM推的JavaBean 构件技术等,使B/S更加成熟.
4.软件重用不同
C/S 程序可以不可避免的整体性考虑, 构件的重用性不如在B/S要求下的构件的重用性好.
B/S 对的多重结构,要求构件相对独立的功能. 能够相对较好的重用.就入买来的餐桌可以再利用,而不是做在墙上的石头桌子
5.系统维护不同
C/S 程序由于整体性, 必须整体考察, 处理出现的问题以及系统升级. 升级难. 可能是再做一个全新的系统
B/S 构件组成,方面构件个别的更换,实现系统的无缝升级. 系统维护开销减到最小.用户从网上自己下载安装就可以实现升级.
6.处理问题不同
C/S 程序可以处理用户面固定, 并且在相同区域, 安全要求高需求, 与操作系统相关. 应该都是相同的系统
B/S 建立在广域网上, 面向不同的用户群, 分散地域, 这是C/S无法作到的. 与操作系统平台关系最小.
7.用户接口不同
C/S 多是建立的Window平台上,表现方法有限,对程序员普遍要求较高
B/S 建立在浏览器上, 有更加丰富和生动的表现方式与用户交流. 并且大部分难度减低,减低开发成本.
8.信息流不同
C/S 程序一般是典型的中央集权的机械式处理, 交互性相对低
B/S 信息流向可变化, BB BC BG等信息、流向的变化, 更像交易中心。
118、Linux下线程,GDI类的解释。
LINUX实现的就是基于核心轻量级进程的"一对一"线程模型,一个线程实体对应一个核心轻量级进程,而线程之间的管理在核外函数库中实现。
GDI类为图像设备编程接口类库。
119、STRUTS的应用(如STRUTS架构)
Struts是采用Java Servlet/JavaServer Pages技术,开发Web应用程序的开放源码的framework。 采用Struts能开发出基于MVC(Model-View-Controller)设计模式的应用构架。 Struts有如下的主要功能: 一.包含一个controller servlet,能将用户的请求发送到相应的Action对象。 二.JSP自由tag库,并且在controller servlet中提供关联支持,帮助开发员创建交互式表单应用。 三.提供了一系列实用对象:XML处理、通过Java reflection APIs自动处理JavaBeans属性、国际化的提示和消息。
120、Jdo是什么?
JDO是Java对象持久化的新的规范,为java data object的简称,也是一个用于存取某种数据仓库中的对象的标准化API。JDO提供了透明的对象存储,因此对开发人员来说,存储数据对象完全不需要额外的代码(如JDBC API的使用)。这些繁琐的例行工作已经转移到JDO产品提供商身上,使开发人员解脱出来,从而集中时间和精力在业务逻辑上。另外,JDO很灵活,因为它可以在任何数据底层上运行。JDBC只是面向关系数据库(RDBMS)JDO更通用,提供到任何数据底层的存储功能,比如关系数据库、文件、XML以及对象数据库(ODBMS)等等,使得应用可移植性更强。
121、内部类可以引用他包含类的成员吗?有没有什么限制?
一个内部类对象可以访问创建它的外部类对象的内容
122、WEB SERVICE名词解释。JSWDL开发包的介绍。JAXP、JAXM的解释。SOAP、UDDI,WSDL解释。
Web ServiceWeb Service是基于网络的、分布式的模块化组件,它执行特定的任务,遵守具体的技术规范,这些规范使得Web Service能与其他兼容的组件进行互操作。
JAXP(Java API for XML Parsing) 定义了在Java中使用DOM, SAX, XSLT的通用的接口。这样在你的程序中你只要使用这些通用的接口,当你需要改变具体的实现时候也不需要修改代码。
JAXM(Java API for XML Messaging) 是为SOAP通信提供访问方法和传输机制的API。
WSDL是一种XML 格式,用于将网络服务描述为一组端点,这些端点对包含面向文档信息或面向过程信息的消息进行操作。这种格式首先对操作和消息进行抽象描述,然后将其绑定到具体的网络协议和消息格式上以定义端点。相关的具体端点即组合成为抽象端点(服务)。
SOAP即简单对象访问协议(Simple Object Access Protocol),它是用于交换XML编码信息的轻量级协议。
UDDI 的目的是为电子商务建立标准;UDDI是一套基于Web的、分布式的、为Web Service提供的、信息注册中心的实现标准规范,同时也包含一组使企业能将自身提供的Web Service注册,以使别的企业能够发现的访问协议的实现标准。
JAVA代码查错
1.
abstract class Name {private String name;public abstract boolean isStupidName(String name) {}}大侠们,这有何错误?
答案: 错。abstract method必须以分号结尾,且不带花括号。
2.
public class Something {void doSomething () {private String s = "";int l = s.length();}}有错吗?
答案: 错。局部变量前不能放置任何访问修饰符(private,public,和protected)。final可以用来修饰局部变量
(final如同abstract和strictfp,都是非访问修饰符,strictfp只能修饰class和method而非variable)。
3.
abstract class Something {private abstract String doSomething ();}这好像没什么错吧?
答案: 错。abstract的methods不能以private修饰。abstract的methods就是让子类implement(实现)具体细节的,怎么可以用private把abstract
method封锁起来呢? (同理,abstract method前不能加final)。
4.
public class Something {public int addOne(final int x) {return ++x;}}这个比较明显。
答案: 错。int x被修饰成final,意味着x不能在addOne method中被修改。
5.
public class Something {public static void main(String[] args) {Other o = new Other();new Something().addOne(o);}public void addOne(final Other o) {o.i++;}}class Other {public int i;}和上面的很相似,都是关于final的问题,这有错吗?
答案: 正确。在addOne method中,参数o被修饰成final。如果在addOne method里我们修改了o的reference
(比如: o = new Other();),那么如同上例这题也是错的。但这里修改的是o的member vairable
(成员变量),而o的reference并没有改变。
6.
class Something {int i;public void doSomething() {System.out.println("i = " + i);}}有什么错呢? 看不出来啊。
答案: 正确。输出的是"i = 0"。int i属於instant variable (实例变量,或叫成员变量)。instant variable有default value。int的default value是0。
7.
class Something {final int i;public void doSomething() {System.out.println("i = " + i);}}和上面一题只有一个地方不同,就是多了一个final。这难道就错了吗?
答案: 错。final int i是个final的instant variable (实例变量,或叫成员变量)。final的instant variable没有default value,必须在constructor (构造器)结束之前被赋予一个明确的值。可以修改为"final int i = 0;"。
8.
public class Something {public static void main(String[] args) {Something s = new Something();System.out.println("s.doSomething() returns " + doSomething());}public String doSomething() {return "Do something ...";}}看上去很完美。
答案: 错。看上去在main里call doSomething没有什么问题,毕竟两个methods都在同一个class里。但仔细看,main是static的。static method不能直接call non-static methods。可改成"System.out.println("s.doSomething() returns " + s.doSomething());"。同理,static method不能访问non-static instant variable。
9.
此处,Something类的文件名叫OtherThing.java
class Something {private static void main(String[] something_to_do) { System.out.println("Do something ...");}}这个好像很明显。
答案: 正确。从来没有人说过Java的Class名字必须和其文件名相同。但public class的名字必须和文件名相同。
10.
interface A{int x = 0;}class B{int x =1;}class C extends B implements A {public void pX(){System.out.println(x);}public static void main(String[] args) {new C().pX();}}答案:错误。在编译时会发生错误(错误描述不同的JVM有不同的信息,意思就是未明确的x调用,两个x都匹配(就象在同时import java.util和java.sql两个包时直接声明Date一样)。对于父类的变量,可以用super.x来明确,而接口的属性默认隐含为public static final.所以可以通过Ax来明确。
11.
interface Playable {void play();}interface Bounceable {void play();}interface Rollable extends Playable, Bounceable {Ball ball = new Ball("PingPang");}class Ball implements Rollable {private String name;public String getName() {return name;}public Ball(String name) {this.name = name; }public void play() {ball = new Ball("Football");System.out.println(ball.getName());}}这个错误不容易发现。
答案: 错。"interface Rollable extends Playable, Bounceable"没有问题。interface可继承多个interfaces,所以这里没错。问题出在interface Rollable里的"Ball ball = new Ball("PingPang");"。任何在interface里声明的interface variable (接口变量,也可称成员变量),默认为public static final。也就是说"Ball ball = new Ball("PingPang");"实际上是"public static final Ball ball = new Ball("PingPang");"。在Ball类的Play()方法中,"ball = new Ball("Football");"改变了ball的reference,而这里的ball来自Rollable interface,Rollable interface里的ball是public static final的,final的object是不能被改变reference的。因此编译器将在"ball = new Ball("Football");"这里显示有错。
JAVA编程题
1.现在输入n个数字,以逗号,分开;然后可选择升或者降序排序;按提交键就在另一页面显示按什么排序,结果为,提供reset
import java.util.*;public class bycomma{public static String[] splitStringByComma(String source){if(source==null||source.trim().equals(""))return null;StringTokenizer commaToker = new StringTokenizer(source,",");String[] result = new String[commaToker.countTokens()];int i=0;while(commaToker.hasMoreTokens()){result[i] = commaToker.nextToken();i++;}return result;}public static void main(String args[]){String[] s = splitStringByComma("5,8,7,4,3,9,1");int[] ii = new int[s.length];for(int i = 0;i<s.length;i++){ii[i] =Integer.parseInt(s[i]);}Arrays.sort(ii);//ascfor(int i=0;i<s.length;i++){System.out.println(ii[i]);}//descfor(int i=(s.length-1);i>=0;i--){System.out.println(ii[i]);}}}2.金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥1011)->(一千零一拾一元整)输出。
package test.format;import java.text.NumberFormat;import java.util.HashMap;public class SimpleMoneyFormat {public static final String EMPTY = "";public static final String ZERO = "零";public static final String ONE = "壹";public static final String TWO = "贰";public static final String THREE = "叁";public static final String FOUR = "肆";public static final String FIVE = "伍";public static final String SIX = "陆";public static final String SEVEN = "柒";public static final String EIGHT = "捌";public static final String NINE = "玖";public static final String TEN = "拾";public static final String HUNDRED = "佰";public static final String THOUSAND = "仟";public static final String TEN_THOUSAND = "万";public static final String HUNDRED_MILLION = "亿";public static final String YUAN = "元";public static final String JIAO = "角";public static final String FEN = "分";public static final String DOT = ".";private static SimpleMoneyFormat formatter = null;private HashMap chineseNumberMap = new HashMap();private HashMap chineseMoneyPattern = new HashMap();private NumberFormat numberFormat = NumberFormat.getInstance();private SimpleMoneyFormat() {numberFormat.setMaximumFractionDigits(4);numberFormat.setMinimumFractionDigits(2);numberFormat.setGroupingUsed(false);chineseNumberMap.put("0", ZERO);chineseNumberMap.put("1", ONE);chineseNumberMap.put("2", TWO);chineseNumberMap.put("3", THREE);chineseNumberMap.put("4", FOUR);chineseNumberMap.put("5", FIVE);chineseNumberMap.put("6", SIX);chineseNumberMap.put("7", SEVEN);chineseNumberMap.put("8", EIGHT);chineseNumberMap.put("9", NINE);chineseNumberMap.put(DOT, DOT);chineseMoneyPattern.put("1", TEN);chineseMoneyPattern.put("2", HUNDRED);chineseMoneyPattern.put("3", THOUSAND);chineseMoneyPattern.put("4", TEN_THOUSAND);chineseMoneyPattern.put("5", TEN);chineseMoneyPattern.put("6", HUNDRED);chineseMoneyPattern.put("7", THOUSAND);chineseMoneyPattern.put("8", HUNDRED_MILLION);}public static SimpleMoneyFormat getInstance() {if (formatter == null)formatter = new SimpleMoneyFormat();return formatter;}public String format(String moneyStr) {checkPrecision(moneyStr);String result;result = convertToChineseNumber(moneyStr);result = addUnitsToChineseMoneyString(result);return result;}public String format(double moneyDouble) {return format(numberFormat.format(moneyDouble));}public String format(int moneyInt) {return format(numberFormat.format(moneyInt));}public String format(long moneyLong) {return format(numberFormat.format(moneyLong));}public String format(Number moneyNum) {return format(numberFormat.format(moneyNum));}private String convertToChineseNumber(String moneyStr) {String result;StringBuffer cMoneyStringBuffer = new StringBuffer();for (int i = 0; i < moneyStr.length(); i++) {cMoneyStringBuffer.append(chineseNumberMap.get(moneyStr.substring(i, i + 1)));}//拾佰仟万亿等都是汉字里面才有的单位,加上它们int indexOfDot = cMoneyStringBuffer.indexOf(DOT);int moneyPatternCursor = 1;for (int i = indexOfDot - 1; i > 0; i--) {cMoneyStringBuffer.insert(i, chineseMoneyPattern.get(EMPTY + moneyPatternCursor));moneyPatternCursor = moneyPatternCursor == 8 ? 1 : moneyPatternCursor + 1;}String fractionPart = cMoneyStringBuffer.substring(cMoneyStringBuffer.indexOf("."));cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("."), cMoneyStringBuffer.length());while (cMoneyStringBuffer.indexOf("零拾") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零拾"), cMoneyStringBuffer.indexOf("零拾") + 2, ZERO);}while (cMoneyStringBuffer.indexOf("零佰") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零佰"), cMoneyStringBuffer.indexOf("零佰") + 2, ZERO);}while (cMoneyStringBuffer.indexOf("零仟") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零仟"), cMoneyStringBuffer.indexOf("零仟") + 2, ZERO);}while (cMoneyStringBuffer.indexOf("零万") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零万"), cMoneyStringBuffer.indexOf("零万") + 2, TEN_THOUSAND);}while (cMoneyStringBuffer.indexOf("零亿") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零亿"), cMoneyStringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);}while (cMoneyStringBuffer.indexOf("零零") != -1) {cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零零"), cMoneyStringBuffer.indexOf("零零") + 2, ZERO);}if (cMoneyStringBuffer.lastIndexOf(ZERO) == cMoneyStringBuffer.length() - 1)cMoneyStringBuffer.delete(cMoneyStringBuffer.length() - 1, cMoneyStringBuffer.length());cMoneyStringBuffer.append(fractionPart);result = cMoneyStringBuffer.toString();return result;}private String addUnitsToChineseMoneyString(String moneyStr) {String result;StringBuffer cMoneyStringBuffer = new StringBuffer(moneyStr);int indexOfDot = cMoneyStringBuffer.indexOf(DOT);cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, YUAN);cMoneyStringBuffer.insert(cMoneyStringBuffer.length() - 1, JIAO);cMoneyStringBuffer.insert(cMoneyStringBuffer.length(), FEN);if (cMoneyStringBuffer.indexOf("零角零分") != -1)//没有零头,加整cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零角零分"), cMoneyStringBuffer.length(), "整");elseif (cMoneyStringBuffer.indexOf("零分") != -1)//没有零分,加整cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零分"), cMoneyStringBuffer.length(), "整");else {if(cMoneyStringBuffer.indexOf("零角")!=-1)cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("零角"),cMoneyStringBuffer.indexOf("零角")+2);// tmpBuffer.append("整");}result = cMoneyStringBuffer.toString();return result;}private void checkPrecision(String moneyStr) {int fractionDigits = moneyStr.length() - moneyStr.indexOf(DOT) - 1;if (fractionDigits > 2)throw new RuntimeException("金额" + moneyStr + "的小数位多于两位。"); //精度不能比分低}public static void main(String args[]) {System.out.println(getInstance().format(new Double(10010001.01)));}}3、继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
答:父类:
package test; public class FatherClass { public FatherClass() { System.out.println("FatherClass Create"); } }子类:
package test; import test.FatherClass; public class ChildClass extends FatherClass { public ChildClass() { System.out.println("ChildClass Create"); } public static void main(String[] args) { FatherClass fc = new FatherClass(); ChildClass cc = new ChildClass(); } }Output result:
C:>java test.ChildClass
FatherClass Create
FatherClass Create
ChildClass Create
4、内部类的实现方式?
答:示例代码如下:
package test; public class OuterClass { private class InterClass { public InterClass() { System.out.println("InterClass Create"); } } public OuterClass() { InterClass ic = new InterClass(); System.out.println("OuterClass Create"); } public static void main(String[] args) { OuterClass oc = new OuterClass(); } }输出结果:
C:>java test/OuterClass InterClass Create OuterClass Create 再一个例题: public class OuterClass { private double d1 = 1.0; //insert code here } You need to insert an inner class declaration at line 3. Which two inner class declarations are valid?(Choose two.) A. class InnerOne{ public static double methoda() {return d1;} } B. public class InnerOne{ static double methoda() {return d1;} } C. private class InnerOne{ double methoda() {return d1;} } D. static class InnerOne{ protected double methoda() {return d1;} } E. abstract class InnerOne{ public abstract double methoda(); }The description is as follows:
一.静态内部类可以有静态成员,而非静态内部类则不能有静态成员。 故A、B 错
二.静态内部类的非静态成员可以访问外部类的静态变量,而不可访问外部类的非静态变量;return d1 出错。故D 错
三.非静态内部类的非静态成员可以访问外部类的非静态变量。 故C 正确
四.答案为C、E
5、Java 的通信编程,编程题(或问答),用JAVA SOCKET编程,读服务器几个字符,再写入本地显示?
答:Server端程序:
package test; import java.NET.*; import java.io.*; public class Server { private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; public Server() { try { ss=new ServerSocket(10000); while(true) { socket = ss.accept(); String RemoteIP = socket.getInetAddress().getHostAddress(); String RemotePort = ":"+socket.getLocalPort(); System.out.println("A client come in!IP:"+Remo ##################################################################################################【第二部分:难度比较大】##################################################################################################某公司Java面试题及部分解答(难度较大)
1.请大概描述一下Vector和ArrayList的区别,Hashtable和HashMap的区别。 (5)
2.请问你在什么情况下会在你的JAVA代码中使用可序列化? (5)
为什么放到HttpSession中的对象必须要是可序列化的? (5)
3.为什么在重写了equals()方法之后也必须重写hashCode()方法? (10)
4. sleep()和wait()有什么区别? (10)
5.编程题:用最有效率的方法算出2乘以17等于多少? (5)
6. JAVA是不是没有内存泄漏问题?看下面的代码片段,并指出这些代码隐藏的问题。 (10)
Object[] elements = new Object[10]; int size; ...public Object pop() { if (size == 0) return null; Object o = elements[--size]; return o; }7.请阐述一下你对JAVA多线程中“锁”的概念的理解。 (10)
8.所有的递归实现都可以用循环的方式实现,请描述一下这两种实现方式各自的优劣。
并举例说明在什么情况下可以使用递归,而在什么情况下只能使用循环而不能使用递归? (5)
9.请简要讲一下你对测试驱动开发(TDD)的认识。 (10)
10.请阐述一下你对“面向接口编程”的理解。 (10)
11.在J2EE中有一个“容器(Container)”的概念,不管是EJB、PICO还是spring都有他们
各自实现的容器,受容器管理的组件会具有有生命周期的特性,请问,为什么需要容器?
它的好处在哪里?它会带来什么样的问题? (15)
12.请阐述一下你对IOC(Inversion of Control)的理解。 (可以以PICO和Spring的IOC作为例子说明他们在实现上各自的特点)(10)
13。下面的代码在绝大部分时间内都运行得很正常,请问在什么情况下会出现问题?问题的根源在哪里? (10)
import java.util.LinkedList; public class Stack { LinkedList list = new LinkedList(); public synchronized void push(Object x) { synchronized(list) { list.addLast( x ); notify(); } } public synchronized Object pop() throws Exception { synchronized(list) { if( list.size() <= 0 ) { wait(); } return list.removeLast(); } } }answer:
.请大概描述一下Vector和ArrayList的区别,Hashtable和HashMap的区别。 (5)线程安全与否
2.请问你在什么情况下会在你的JAVA代码中使用可序列化? (5)cluster中session复制,缓存persist与reload
为什么放到HttpSession中的对象必须要是可序列化的?(5)没必须,不过session反序列化过程会导致对象不可用.
3.为什么在重写了equals()方法之后也必须重写hashCode()方法? (10)API规范
4. sleep()和wait()有什么区别? (10)前者占用CPU,后者空闲CPU
5.编程题:用最有效率的方法算出2乘以17等于多少? (5)17>>1
6. JAVA是不是没有内存泄漏问题?看下面的代码片段,并指出这些代码隐藏的问题。 (10)不是
...
...没发现内存泄漏的问题
7.请阐述一下你对JAVA多线程中“锁”的概念的理解。 (10)同步因子,在某段代码上增加同步因子,那么整个JVM内部只能最多有一个线程执行这段,其余的线程按FIFO方式等待执行.
8.所有的递归实现都可以用循环的方式实现,请描述一下这两种实现方式各自的优劣。
并举例说明在什么情况下可以使用递归,而在什么情况下只能使用循环而不能使用递归?(5)没发现所有的递归都可以用循环实现的,尤其是那种不知道循环重数的递归算法.递归的优点是简炼,抽象性好;循环则更直观.递归一般用于处理一级事务能转化成更简的二级事务的操作.归纳不出二级事务或者二级事务更复杂的情况不能用.
9.请简要讲一下你对测试驱动开发(TDD)的认识。 (10)不认识
10.请阐述一下你对“面向接口编程”的理解。 (10)1,利于扩展;2,暴露更少的方法;
11.在J2EE中有一个“容器(Container)”的概念,不管是EJB、PICO还是Spring都有他们
各自实现的容器,受容器管理的组件会具有有生命周期的特性,请问,为什么需要容器?
它的好处在哪里?它会带来什么样的问题?(15)组件化,框架设计...
12.请阐述一下你对IOC(Inversion of Control)的理解。 (可以以PICO和Spring的IOC作为例子说明他们在实现上各自的特点)(10)不理解
13。下面的代码在绝大部分时间内都运行得很正常,请问在什么情况下会出现问题?问题的根源在哪里?(10)wait和notify使用目的不能达到,wait()的obj,自身不能notify().出题人对wait和notify机制不够理解.
import java.util.LinkedList;public class Stack {LinkedList list = new LinkedList();public synchronized void push(Object x) {synchronized(list) { list.addLast( x );notify();}}public synchronized Object pop()throws Exception { synchronized(list) { if( list.size() <= 0 ) {wait();}return list.removeLast();}}}你拿了多少分?
1.请大概描述一下Vector和ArrayList的区别,Hashtable和HashMap的区别。 (5)
// thread-safe or unsafe, could contain null values or not
2.请问你在什么情况下会在你的JAVA代码中使用可序列化? (5)
为什么放到HttpSession中的对象必须要是可序列化的? (5)
// save, communicate
3.为什么在重写了equals()方法之后也必须重写hashCode()方法? (10)
// implementations of dictionaries need hashCode() and equals()
4. sleep()和wait()有什么区别? (10)
// threads communication: wait() and notifyAll()
5.编程题:用最有效率的方法算出2乘以17等于多少? (5)
// 2<<4+2
6. JAVA是不是没有内存泄漏问题?看下面的代码片段,并指出这些代码隐藏的问题。 (10)
...
Object[] elements = new Object[10];int size;...public Object pop() {if (size == 0)return null;Object o = elements[--size];return o;}// elements[size] = null;7.请阐述一下你对JAVA多线程中“锁”的概念的理解。 (10)
// optimistic lock, pessimistic lock, signal, dead lock, starvation, synchronization
8.所有的递归实现都可以用循环的方式实现,请描述一下这两种实现方式各自的优劣。
并举例说明在什么情况下可以使用递归,而在什么情况下只能使用循环而不能使用递归? (5)
// recursive: when you need a stack and stack memory is enough
// non-recursive: when you need a queue
9.请简要讲一下你对测试驱动开发(TDD)的认识。 (10)
// write unit testing code first
10.请阐述一下你对“面向接口编程”的理解。 (10)
// adapter, listener, bridge, decorator, proxy... patterns
11.在J2EE中有一个“容器(Container)”的概念,不管是EJB、PICO还是Spring都有他们
各自实现的容器,受容器管理的组件会具有有生命周期的特性,请问,为什么需要容器?
它的好处在哪里?它会带来什么样的问题? (15)
// encapsulation
12.请阐述一下你对IOC(Inversion of Control)的理解。 (可以以PICO和Spring的IOC作为例子说明他们在实现上各自的特点)(10)
// reduce classes' dependencies
13。下面的代码在绝大部分时间内都运行得很正常,请问在什么情况下会出现问题?问题的根源在哪里? (10)
import java.util.LinkedList;public class Stack {LinkedList list = new LinkedList();public synchronized void push(Object x) {synchronized(list) {list.addLast( x );notify();}}public synchronized Object pop()throws Exception {synchronized(list) {if( list.size() <= 0 ) {wait();}return list.removeLast();}}}// dead lock, synchronized on both 'list' and 'this'以上所述是小编给大家介绍的Java面试题及答案集锦(基础题122道,代码题19道),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!