Collection of Java interview questions and answers (122 basic questions and 19 code questions)

A collection of java basic interview questions and answers (122 basic questions and 19 code questions). The details are as follows:

1. What are the characteristics of object-oriented

1. Abstraction:

Abstraction is to ignore those aspects of a topic that are not related to the current goal, so as to pay more attention to those aspects related to the current goal. Abstract does not intend to understand all the problems, but only select some of them without some details for the time being. Abstraction includes two aspects: process abstraction and data abstraction.

2. Succession:

Inheritance is a hierarchical model of connecting classes, and allows and encourages the reuse of classes. It provides a way to clearly express commonalities. A new class of an object can be derived from an existing class. 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, and the original class is called the base class (parent class) of the new class. The 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 surround the process and data, and access to the data can only be through the defined interface. Object oriented computing begins with the basic concept that the real world can be described as a series of fully autonomous and encapsulated objects that access other objects through a protected interface.

4. Polymorphism:

Polymorphism means that different objects are allowed to respond to the same message. Polymorphism includes parametric polymorphism and inclusion polymorphism. Polymorphic language has the advantages of flexibility, abstraction, behavior sharing and code sharing, which solves the problem of application function homonymy.

2. Is string the most basic data type?

Basic data types include byte, int, char, long, float, double, Boolean, and short.

java. Lang. string class is of final type, so it cannot inherit or modify this class. To improve efficiency and save space, we should use the StringBuffer class

3. What's the difference between int and integer

Java provides two different types: reference type and primitive type (or built-in type). Int is the primitive 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 and primitive types behave completely differently, and they have different semantics. Reference types and primitive types have different characteristics and usages. They include: size and speed, which type of data structure this type is stored in, and the default value specified when reference types and primitive types are used as instance data of a class. The default value of object reference instance variables is null, while the default value of original type instance variables is related to their types.

4. The difference between string and StringBuffer

The Java platform provides two classes: string and StringBuffer, which can store and manipulate strings, that is, character data containing multiple characters. This string class provides a string whose value cannot be changed. The string provided by this StringBuffer class can be modified. When you know that the character data will change, 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?

An exception represents an abnormal state that may occur during program operation. A runtime exception represents an exception that may be encountered in the normal operation of a virtual machine. It is a common operation error. The java compiler requires that methods must declare that they throw possible non runtime exceptions, but it does not require that they declare that they throw uncapped runtime exceptions.

6. Tell the life cycle of servlets and the difference between servlets 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 corresponding to the request (doget, dopost), etc. when the server decides to destroy the instance, it calls its destroy method. The difference from CGI is that the servlet is in the server process. It runs its service method through multithreading. An instance can serve multiple requests, and its instance is generally not destroyed. CGI generates a new process for each request, which is destroyed after the service is completed, So it is less efficient than servlet.

7. Name the storage performance and characteristics of ArrayList, vector and LinkedList

ArrayList and vector use array to store data. The number of elements in this array is larger than the actual stored data, so as to add and insert elements. They both allow elements to be indexed directly by sequence number, but inserting elements involves memory operations such as array element movement, so index data is fast and inserting data is slow, Because vector uses the synchronized method (thread safety), its performance is usually worse than ArrayList, while LinkedList uses a two-way linked list to store. Indexing data by serial number requires forward or backward traversal, but only the front and rear items of this item need to be recorded when inserting data, so the insertion speed is faster.

8. What technologies are EJB implemented based on? And tell the difference between sessionbean and entitybean, and the difference between statefulbean and statelessbean.

EJB includes session bean, entity bean and message driven bean, which are implemented based on JNDI, RMI, Jat and other technologies.

Sessionbean is used in J2EE applications to complete some server-side business operations, such as accessing database and calling other EJB components. Entitybean is used to represent the 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, an entitybean is a persistent object that represents an object view of an entity stored in persistent storage, or an entity implemented by an existing enterprise application.

Session beans can also be subdivided into stateful session beans and stateless session beans, both of which can execute the system logic in the method. The difference is that stateful session beans can record the caller's state. Therefore, generally speaking, an user will have a corresponding entity of stateful session beans. Although stateless session bean is also a logical component, it is not responsible for recording the user's state, that is, when the user calls stateless session bean, the EJB container will not find the entity of a specific stateless session bean to execute this method. In other words, it is likely that when several users execute the methods of a stateless session bean, the instance of the same bean will be executing. In terms of memory, compared with stateless session bean, stateful session bean will consume more memory of J2EE server. However, the advantage of stateful session bean is that it can maintain the user's state.

9. The difference between collections and collections.

Collection is the superior interface of a collection class, and its inherited interfaces mainly include set and list

Collections is a help class for collection classes. It provides a series of static methods to search, sort, thread safety and other operations on various collections.

10. The difference between & & and & &.

&Is a bitwise operator, indicating bitwise and operation, & & is a logical operator, indicating logical and.

11. The difference between HashMap and hashtable.

HashMap is a lightweight implementation of hashtable (non thread safe implementation). They have completed the map interface. The main difference is that HashMap allows null keys. Due to non thread safety, the efficiency may be higher than that of hashtable.

HashMap allows null as the key or value of an entry, while hashtable does not.

HashMap removes the contents method of hashtable and changes it to containsvalue and containskey. Because the contains method is easy to be misunderstood.

Hashtable inherits from the dictionary class, and HashMap is java 1 2 an implementation of the introduced map interface.

The biggest difference is that the hashtable method is synchronized, while the HashMap method is not. When multiple threads access the hashtable, they do not need to synchronize their own methods, but the HashMap must provide external synchronization for it (if it is ArrayList: List LST = collections. Synchronizedlist (New arraylist()); In case of HashMap: Map = collections synchronizedMap(new HashMap());)。

Hashtable and HashMap adopt the same hash / rehash algorithm, so the performance will not be very different.

12. The difference between final, finally and finalize.

Final is used to declare attributes, methods and classes, respectively indicating that attributes are immutable, methods cannot be overridden 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. When the garbage collector executes, it will call this method of the recycled object. It can override this method to provide other resource recycling during garbage collection, such as closing files.

13. What's the difference between sleep () and wait ()?

Sleep is a method of thread class, which causes this thread to suspend execution for a specified time and give execution opportunities to other threads, but the monitoring status remains and will be automatically restored after that time. Calling sleep will not release the object lock.

Wait is a method of object class. Calling the wait method on this object causes this thread to give up the object lock and enter the waiting lock pool waiting for this object. This thread enters the object lock pool only after issuing the notify method (or notifyAll) for this object, ready to obtain the object lock and enter 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 classes, 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 overridden. When an object of a subclass uses this method, the definition in the subclass will be called. For it, the definition in the parent class is "masked". If multiple methods with the same name are defined in a class, they either have different parameter numbers or different parameter types, it is called method overloading. The overloaded method can change the type of the return value.

15. What is the difference between error and exception?

Error indicates 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. In other words, it means that if the program works normally, it will never happen.

16. What are the similarities and differences between synchronous and asynchronous, and under what circumstances are they used respectively? Give an example.

If the data will be shared between processes. For example, the data being written may be read by another thread later, or the data being read may have been written by another thread, then these data are shared data and must be accessed synchronously.

When an application calls a method that takes a long time to execute on an object and does not want the program to wait for the return of the method, asynchronous programming should be used. In many cases, asynchronous approach is often more efficient.

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 (abstract class), which is used to create a class that embodies some basic behaviors and declare methods for the class, but the class cannot be implemented in the class. You cannot create an instance of the abstract class. However, you can create a variable whose type is an abstract class and let it point to an instance of a specific subclass. There can be no abstract constructor or abstract static method. Ab Subclasses of the strat class provide implementations for all abstract methods in their parent classes, 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.

Interface (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 an interface are abstract and none has a program body. An interface 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 When a class implements a special interface, Its definition (that is, the program body gives) all the methods of this interface. Then, it can call the methods of the interface on any object of the class that implements the interface. Due to the abstract class, it allows the use of the interface name as the type of the reference variable. The usual dynamic binding will take effect. The reference can be converted to or from the interface type, and the instanceof operator can be used to determine Determines whether the class of an object implements an interface.

18. What's the difference between heap and stack.

Stack is a kind of linear collection. The operations of adding and deleting elements should be completed in the same section. The stack is processed in a last in first out manner.

The heap is a constituent element of the stack

19. The difference between forward and redirect

Forward is that the server requests resources. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends these contents to the browser. The browser doesn't know 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 according to logic to tell the browser to re request the address. Generally speaking, the browser will re request with all the parameters just requested, so the session and request parameters can be obtained.

20. What is the difference between EJB and java bean?

Java beans are reusable components. There is no strict specification for Java beans. Theoretically, any Java class can be a bean. But usually, Because Java beans are created by containers (such as Tomcat), so Java beans should have a parameterless constructor. In addition, Java beans usually implement the serializable interface to realize the persistence of beans. Java beans are actually equivalent to the local in-process COM components in microsoft com model, which cannot be accessed by cross processes. Enterprise Java beans are equivalent to DCOM, that is, distributed components. They are Java based remote components Process method invocation (RMI) technology, so EJBs can be accessed remotely (cross process, cross computer), but EJBs must be deployed in places such as webspere

In a container like Weblogic, EJB clients never access the real EJB components directly, but through their container. EJB container is the proxy of EJB components, which are created and managed by the container. The client accesses the real EJB component through the container.

21. Differences between static nested class and inner class.

Static nested class is an internal class declared static. It can be instantiated independent of the external class instance. However, the internal class can only be instantiated after the external class is instantiated.

22. What is the difference between dynamic and static include in JSP?

Dynamic include is implemented with jsp: include action < jsp: include page = "included. JSP" flush = "true" / > it always checks the changes in the contained files, which is suitable for containing dynamic pages, and can take parameters.

Static include is implemented with include pseudo code. It will not check the changes of the contained files. It is applicable to the static page <% @ include file = "included. HTM"% >

23. When to use assert.

Assertion is a common debugging method in software development, which is supported by many development languages. In the implementation, assertion is a statement in the program, which checks a Boolean expression. A correct program must ensure that the value of the Boolean expression is true; If the value is false, it indicates that the program is 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. The assertion check is usually turned on during development and testing. To improve performance, the assertion check is usually turned off after the software is released.

24. What is GC? Why GC?

GC means garbage collection Memory processing is a place where programmers are prone to problems. Forgetting or wrong memory recovery will lead to program or system instability or even crash. The GC function provided by java can automatically monitor whether the object exceeds the scope, so as to achieve the purpose of automatic memory recovery. The Java language does not provide a display operation method to release the 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 needs to be cast) short S1 = 1; S1 + = 1; (it can be compiled correctly)

26、Math. What is round (11.5) equal to? Math. What is round (- 11.5) equal to?

Math. round(11.5)==12 Math. round(-11.5)==-11

The round method returns the long integer closest to the parameter. Add 1 / 2 to the parameter to find its floor

27、String s = new String("xyz"); How many string objects have been created?

Two

28. Four threads are designed, in which two threads increase 1 for J each time, and the other two threads decrease 1 for J each time. Write a program.

The following program uses internal classes to implement threads, and does not consider the order when increasing or decreasing J.

29. Does java have goto?

Reserved words in Java are not used in Java now.

30. Whether to start a thread with run() or start()?

Starting a thread is to call the start () method to make the virtual processor represented by the thread in a runnable state, which means that it can be scheduled and executed by the JVM. This does not mean that the thread will run immediately. The run () method can stop a thread by generating a flag that must exit.

31. How do EJBs (sessionbeans, entitybeans) describe their life cycles and manage transactions?

Sessionbean: the life cycle of stateless session bean is determined by the container. When the client sends a request to create an instance of a bean, the EJB container does not have to create a new instance of the bean for the client to call, but just find an existing instance to provide to the client. When a 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. In the future, when this client calls the method of stateful session bean, the container will assign the call to the bean instance associated with this client.

Entitybeans: entity beans can survive for a relatively long time, and the 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 lifecycle can be managed by the container or beans themselves.

EJB manages practices through the following technologies: object practice service (OTS) of object management organization (OMG), transaction service (JTS) of Sun Microsystems, Java transaction API (JTA), and XA interface of development group (x / open).

32. What are the application servers?

BEA WebLogic Server,IBM WebSphere Application Server,Oracle9i Application Server,jBoss,Tomcat

33. Give me the most common runtime exception.

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. Is the interface inheritable? Can abstract classes implement interfaces? Can an abstract class inherit an entity class?

Interfaces can inherit interfaces. Abstract classes can implement interfaces. Whether an abstract class can inherit an entity class or not, but the premise is that the entity class must have an explicit constructor.

35. Do list, set and map inherit from the collection interface?

List, set yes, map no

36. What is the working mechanism of data connection pool?

When the J2EE server starts, a certain number of pool connections will be established and maintained at least this number of pool connections. When a client program needs a connection, the pool driver returns an unused pool connection and marks it as busy. If there are currently no idle connections, the pool driver will create a certain number of new connections. The number of new connections is determined by the configuration parameters. When the pool connection used is called, the pool driver will mark this connection table as idle, and other calls can use this connection.

37. Can the abstract method be static, native, and synchronized at the same time? Not at all

38. Does the array have a length () method? Does string have a length () method?

The array does not have a length () method, but has a length attribute. String has a length () method.

39. Elements in a set cannot be repeated, so what method is used to distinguish whether they are repeated or not? Is it = = or equals()? What's the difference between them?

If the elements in the set cannot be repeated, use the iterator () method to distinguish whether they are repeated or not. Equals() is to judge whether two sets are equal.

The equals () and = = methods determine whether the reference value points to the same object. Equals () is overridden in the class in order to return the true value when the contents and types of the two separate objects match.

40. Can the constructor be overridden?

The constructor constructor cannot be inherited, so overriding cannot be overridden, but it can be overloaded.

41. Can I inherit string class?

String class is 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 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 after the try be executed and when, before or after return?

It will be executed before return.

44. Programming problem: how much is 2 multiplied by 8 calculated by the most efficient method?

2 << 3

45. Two objects have the same value (x.equals (y) = = true), but they can have different hash codes, right?

No, it has the same hash code.

46. When an object is passed to a method as a parameter, the method can change the properties of the object and return the changed results. Is this value transfer or reference transfer?

Is value passing. The Java programming language has only value passing parameters. When an object instance is passed to a method as a parameter, the value of the parameter is a reference to the object. The content of the 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 the object? No, a synchronized method of an object can only be accessed by one thread.

48. Programming problem: write a singleton.

Singleton mode is mainly used to ensure that there is only one instance of a class in Java applications.

The general singleton mode usually has several forms:

The first form: define a class whose constructor is private. It has a static private variable of this class. When the class is initialized, obtain the reference to it through a public getInstance method, and then call the method.

The second form:

Other forms:

Define a class whose constructor is private and all methods are static.

It is generally believed that the first form is safer

49. Similarities and differences between Java interface and C + + virtual class.

Because Java does not support multiple inheritance, and it is possible that a class or object needs to use methods or properties in several classes or objects, the existing single inheritance mechanism can not meet the requirements. Interfaces are more flexible than inheritance because there is no implementation code in the interface. When a class implements an interface, it should implement all the methods and properties in the interface. The properties in the interface are public static by default, and all methods are public by default A class can implement multiple interfaces.

50. Simple principle and application of exception handling mechanism in Java.

When a java program violates the semantic rules of Java, the Java virtual machine will represent the error as an exception. Violation of semantic rules includes two cases. One is the built-in semantic check of Java class library. For example, if the array subscript is out of bounds, an indexoutofboundsexception will be raised; NullPointerException is thrown when accessing a null object. Another case is that Java allows programmers to extend this semantic check. Programmers can create their own exceptions and freely choose when to throw exceptions with the throw keyword. All exceptions are Java Subclass of lang. impossible.

51. Advantages and principles of waste recycling. Two recovery mechanisms are considered.

A remarkable feature of Java language is the introduction of garbage collection mechanism, which solves the most troublesome problem of memory management for 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 object references have "scope". Garbage collection can effectively prevent memory leakage and effectively use available memory. The garbage collector usually runs as a separate low-level thread to clear and recycle the dead or unused objects in the memory heap under unpredictable circumstances. Programmers cannot call the garbage collector to garbage collect one or all objects in real time. The recycling mechanisms include generational replication garbage collection, tag garbage collection and incremental garbage collection.

52. Please say what you know about thread synchronization methods.

Wait (): put a thread in a waiting state and release the lock of the held object.

Sleep (): it is a static method to make a running thread sleep. Call this method to catch the interruptedexception exception.

Notify(): wake up a thread in a waiting state. Note that when this method is called, it cannot wake up a thread in a waiting state exactly, but the JVM determines which thread to wake up, not by priority.

Allnotity(): wake up all the threads in the waiting state. Note that instead of giving all the wake-up threads an object lock, they are allowed to compete.

53. What are the collection classes you know? Main methods?

The most commonly used collection classes are list and map. The specific implementation of list includes ArrayList and vector. They are variable size lists, which are more suitable for building, storing and operating element lists of any type of objects. List is suitable for accessing elements by numeric index.

Map provides a more general element storage method. The map collection class is used to store element pairs (called keys and values), where each key is mapped to a value.

54. Describe the principle and mechanism of loading class files by JVM?

Class loading in JVM is implemented by classloader and its subclasses. Java classloader is an important component of Java runtime system. It is responsible for finding and loading classes in class files at run time.

55. Can a Chinese character be stored in a char variable? Why?

It can be defined as a Chinese, because Java is encoded in Unicode, and a char accounts for 16 bytes, so it is no problem to put a Chinese

56. There are several implementation methods of multithreading. What are they? There are several ways to implement synchronization. What are they?

There are two ways to implement multithreading: inheriting the thread class and implementing the runnable interface

There are two ways to implement synchronization: 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, It also provides several methods for setting the response 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 to enable you to send back the output results to the browser. Pagecontext represents a javax.servlet.jsp.pagecontext object. It is an API for accessing a variety of namespace and servlet related objects, and encapsulates the general servlet related functions Law. A session represents a javax servlet. http. Httpsession object. Session can store user status information, and application 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 this page

58. The basic concept of thread, the basic state of thread and the relationship between states

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. Threads in java have four states: running, ready, suspended and end.

59. Common instructions of JSP

60. Under what circumstances do you call doget() and dopost()?

Doget() is called when the method attribute in the form tag in the JSP page is get, and dopost() is called when it is post.

61. Servlet life cycle

The web container loads the servlet and the lifecycle begins. Initialize the servlet by calling the init () method of the servlet. By calling the service () method, different do * * * () methods are called according to different requests. At the end of the service, the web container calls the destroy () method of the servlet.

62. How to realize the single thread mode of servlet

63. Method of object transfer between pages

Request, session, application, cookie, etc

64. What are the similarities and differences between JSP and servlet, and what is the relationship between them?

JSP is an extension of Servlet Technology. In essence, JSP is a simple way of servlet, which emphasizes the appearance expression of application. JSP is "servlet like" after compilation. The main difference between servlet and JSP is that the application logic of servlet is in java files and completely separated from HTML in the presentation layer. In the case of JSP, Java and HTML can be combined into one extension JSP file. JSP focuses on view, and servlet is mainly used for control logic.

65. Four session tracking technologies

Session scope servlets JSP page description

Page no represents the objects and attributes related to a page. A page is represented by a compiled java servlet class (with any include instruction but no include action). This includes both servlets and JSP pages compiled into servlets

Request represents the objects and properties related to a request issued by a web client. A request may span multiple pages and involve multiple web components (due to the relationship between the forward instruction and the include action)

Session represents objects and properties related to a user experience used for a web client. A web session can and often requests across multiple clients. Application represents objects and properties related to the entire web application. This is essentially a global scope that spans the entire web application, including multiple pages, requests, and sessions

66. Main methods of request object:

SetAttribute (string name, object): set the parameter value of the request with name getattribute (string name): return the attribute value specified by name getattributenames(): return the name collection of all attributes of the request object, and the result is an enumerated instance getcookies(): return all cookie objects of the client, The result is a cookie array getcharacterencoding(): return the character encoding method in the request getcontentlength(): return the length of the body of the request getheader (string name): obtain the file header information defined by the HTTP protocol getheaders (string name): return all the values of the request header with the specified name, The result is an enumerated instance getheadernames(): returns the name of all request headers. The result is an enumerated instance getinputstream(): returns the requested input stream, Getmethod(): get the method of transmitting data from the client to the server. Getparameter (string name): get the parameter value specified by name transmitted from the client to the server. Getparameternames(): get the names of all parameters transmitted from the client to the server, The result is an enumerated instance getparametervalues (string name): get all the values of the parameters specified by name getprotocol(): get the protocol name on which the client transmits data to the server getquerystring(): get the query string getrequesturi(): get the client address issuing the request string getremoteaddr() : get the IP address of the client getremotehost(): get the name of the client getsession ([Boolean create]): return the session related to the request getservername(): get the name of the server getservletpath(): get the path of the script file requested by the client getserverport(): get the port number of the server removeattribute (string name) : delete an attribute in the request

67. Is J2EE technology or platform or 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. In the process of web application development, we often encounter outputting some encoded characters, such as iso8859-1. How to output a certain encoded string?

69. Briefly describe the difference between logical operation (&, |, ^) and conditional operation (& &, |).

The main differences are as follows:

a. Conditional operations can only operate Boolean, while logical operations can operate not only Boolean, but also numeric

b. Logic operation will not produce short circuit

70. How many forms do XML document definitions take? What is the essential difference between them? What are the ways to parse XML documents?

a: Two forms of DTD schema,

b: Essential difference: schema itself is XML and can be parsed by XML parser (which is also the fundamental purpose of developing schema from DTD),

c: Dom, sax, Stax and other DOM: when dealing with large files, its performance degrades very badly. This problem is caused by the tree structure of DOM, which occupies a lot of memory, and DOM must load the whole document into memory before parsing the file, which is suitable for random access to XML. Sax: not in DOM, Sax is an event driven XML parsing method. It reads XML files sequentially and does not need to load the entire file at once. When encountering problems such as the beginning of the file, the end of the document, or the beginning and end of the tag, it will trigger an event. The user processes the XML file by writing processing code in its callback event, which is suitable for sequential access to XML

STAX:Streaming API for XML (StAX)

71. Briefly describe synchronized and Java util. concurrent. locks. The similarities and differences between lock?

Main similarities: lock can complete all functions realized by synchronized

Main differences: lock has more precise thread semantics and better performance than synchronized. Synchronized will automatically release the lock, and the lock must be released manually by the programmer, and must be released in the finally clause.

72. EJB role and three objects

A complete EJB based distributed computing structure consists of six roles, which can be provided by different developers. The work of each role must follow the EJB specification provided by Sun company to ensure their compatibility. The six roles are EJB component developer (enterprise bean provider), application assembler (application assembler), deployer (deployer), EJB server provider (EJB server provider), EJB container provider (EJB container provider) and system administrator. The three objects are remote (local) interface and home (localhome) interface, bean class

73. Services provided by EJB container

It mainly provides services such as declaration cycle management, code generation, continuity management, security, transaction management, lock and release management.

74. What are the operations prohibited in the EJB specification?

1. Thread and thread API cannot be operated (thread API refers to methods of non Thread objects, such as notify, wait, etc.), 2 Cannot operate AWT, 3 Unable to realize server function, 4 Cannot access static generics, 5 Cannot use IO operation to directly access the file system, 6 Unable to load local library, 7. This cannot be used as a variable and returned, 8 Cannot loop call.

75. Main functions of remote interface and home interface

The remote interface defines business methods, which are used by EJB clients to call business methods. The home interface is an EJB factory used to create and remove lookup EJB instances

76. Life cycle of bean instance

Buffer pool management generally exists for stateless session beans, entity beans and message driven beans, while cache management exists for entity beans and statefull session beans, which usually includes creating instances, setting context Create EJB object (create), business method call, remove and other processes. For beans with buffer pool management, the instance is not cleared from memory after create, but the buffer pool scheduling mechanism is used to continuously reuse the instance. For beans with cache management, the state of beans is maintained and the number of instances in memory is limited through activation and deactivation mechanisms.

77. EJB activation mechanism

Take stateful session bean as an example: its cache size determines the number of bean instances that can exist simultaneously in memory. According to MRU or NRU algorithm, instances migrate between activated and deactivated states. The activation mechanism is that when the client calls an EJB instance business method, If the corresponding EJB object finds that it does not bind the corresponding bean instance, it will reply (activate) the instance from its deactivated bean store (store the instance through the serialization mechanism). The corresponding ejbactive and ejbpassivate methods will be called before the state changes.

78. Several types of EJBs

Session beans, entity beans, message driven beans, session beans can be divided into stateful and stateless. Entity beans can be divided into bean managed persistence (BMP) and container managed persistence (CMP)

79. Several basic steps of calling EJB object at customer service end

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 a remote interface, and call its business method through the remote interface.

80. How to specify the memory size for Weblogic?

In the script for starting Weblogic (located in the startservername under the corresponding server directory of domian), add set mem_args = - xms32m - xmx200m to adjust the minimum memory to 32m and the maximum memory to 200m

81. How to set the hot start mode (development mode) and product release mode of Weblogic?

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 commonv file to add set production_ MODE=true。

82. How to start without entering user name and password?

Modify the service startup file and add WLS_ User and WLS_ PW item. You can also boot Add encrypted user name and password to the properties file

83. In the Weblogic management console, after configuring JMS, EJB or connection pool and other related information for an application domain (or a website, domain), what file is actually saved in?

Config. Saved in this domain XML file, which is the core configuration file of the server.

84. What is the default directory structure of a domain in Weblogic? For example, a simple hello world JSP into what directory, and then you can enter http: / / host on the browser: port number / / helloword JSP can see the running results? For another example, what if you use a JavaBean written by yourself? Domain directory server directory applications, where the application directory can be accessed as an application. If it is a web application, the application directory needs to meet the requirements of the web application directory, JSP files can be directly placed in the application directory, and Java beans need to be placed in the classes directory of the WEB-INF directory of the application directory, Setting the default application of the server can be realized without entering the application name on the browser.

85. What configuration files are involved in publishing EJBs in Weblogic

Different types of EJBs involve different configuration files, including EJB jar xml,weblogic-ejb-jar. Xmlcmp entity beans generally also need Weblogic CMP RDBMS jar xml

86. How to configure SSL and client authentication in Weblogic, or how to configure SSL in J2EE (standard)

Demoidentity. Is used in the default installation JKS and demotrust JKS keystore implements SSL. You need to configure the server to use enable SSL and configure its port. In the product mode, you need to obtain private keys and digital certificates from Ca, create identity and trust keystore, and load the obtained keys and digital certificates. You can configure whether this SSL connection is one-way or two-way.

87. How to view EJBs published in Weblogic?

You can use the administrative console to view all published EJBs in its deployment

88. What is CORBA? What is the purpose?

CORBA standard is a common object request broker architecture, which is standardized by object management group (OMG). It consists of interface definition language (IDL), language binding (binding) and protocols that allow interoperability between applications. Its purpose is to write in different programming languages, run in different processes, and develop for different operating systems.

89. What are some common patterns in J2EE that you are familiar with or have heard of? And some views on design patterns

Session Facade Pattern: use sessionbean to access entitybean message facade pattern: realize asynchronous calling EJB command pattern: use command JavaBeans to replace sessionbean, Achieve lightweight access to data transfer object factory: simplify entitybean data provision features through dto factory generic attribute access: simplify entitybean data provision features through attributeaccess interface business interface: simplify entitybean data provision features through remote (local) interfaces and bean classes implement the same interface specification business logic consistency. The design of EJB architecture will directly affect the performance, scalability, maintainability, component reusability and development efficiency of the system. The more complex the project is, the larger the project team is, the more important the good design is.

90. Talk about the difference between persistent and non persistent when developing message beans in Weblogic

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 the MDB is available, and the non persistent message will be discarded.

91. Which methods are generally implemented during servlet execution?

92. What are the common design patterns of J2EE? Explain the factory mode.

There are 23 design patterns in Java:

Factory, builder, factory method, prototype, singleton, facade, adapter, bridge, composite, decorator, Flyweight (meta mode), proxy mode, command mode, interpreter mode, visitor mode, iterator mode, mediator mode, memo mode, observer mode, state mode, strategy mode, template method (template method mode), chain of responsibility (responsibility chain mode) factory mode: factory mode is a frequently used mode. Classes implemented according to the factory mode can generate instances of a class in a group of classes according to the provided data. Usually, this group of classes has a common abstract parent class and implements the same methods, but these methods perform different operations for different data. First, you need to specify A base class whose subclasses implement 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 conditions. When the subclass instance is obtained, the developer can call the method in the base class without considering which subclass instance is returned.

93. Does EJB need to directly implement its business interface or home interface? Please briefly explain the reasons.

The remote interface and home interface do not need to be implemented directly. Their implementation code is generated by the server. During program operation, the corresponding implementation class will be used as an instance of the corresponding interface type.

94. What are the sorting methods? Please list. Using java to achieve a quick sort.

Sorting methods include: insert sort (direct insert sort, Hill sort), exchange sort (bubble sort, quick sort), select sort (direct select sort, heap sort), merge sort, and assign pseudo code for quick sort (box sort, cardinal sort).

// use the quick sort method to sort a [0: n - 1], select an element from a [0: n - 1] as M I d l e, which is the fulcrum, and 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, The elements in right are greater than or equal to the fulcrum. Recursively use the quick sort method to sort left. Recursively use the quick sort method to sort right. The result is l e f t + M I d l e + r i g h t

95. Please explain (or briefly describe) the following terms commonly used in J2EE

Web container: for application components in it (JSP, servlet) provides an environment that enables JSP and servlet to interact directly with the environment variable interface in the container without paying attention to other system problems. It is mainly implemented by web server, such as tomcat, Weblogic, WebSphere, etc. the interface provided by the container strictly complies with the web application standard in J2EE specification. We call the web server complying with the above standards web server in J2EE Container. EJB Container: enterprise java bean container. It has more industry characteristics. It provides various management functions to the component EJB running in it. As long as the EJB meeting the J2EE specification is put into the container, it will be efficiently managed by the container. And system level services can be obtained through ready-made interfaces. For example, mail service, transaction management. JNDI: (Java Naming & Directory Interface) Java Naming directory service. Its main function is to provide a directory system for applications in other places to leave their own indexes on it, so as to meet the function of quickly finding and locating distributed applications. JMS: (Java Message Service) Java message service. It mainly realizes the communication between various applications, including point-to-point and broadcast. JTA: (Java transaction API) Java transaction service. It provides various distributed transaction services. Applications only need to call the interfaces provided. Java: (Java action framework) Java security authentication framework. It provides some security control frameworks. It allows developers to implement their own personalized security control policies through various deployment and customization. RMI / IIOP: (remote method invocation / Internet object request mediation protocol) they are mainly used to call services remotely. For example, there is a program running on a remote computer that provides stock analysis services, and we can call it directly on the local computer. Of course, this requires certain specifications to communicate between heterogeneous systems. RMI is Java Unique.

96. How does the Java language handle exceptions? What are the meanings of the keywords: throws, throw, try, catch and finally? Can exceptions be thrown in the try block?

Java handles exceptions through object-oriented methods, classifies various exceptions, and provides a good interface. In Java, each exception is an object that is an instance of the throwable class or other subclasses. When a method has an exception, it throws an exception object, which contains exception information. The method calling this object can catch the exception and handle it. Java exception handling is implemented through five Keywords: try, catch, throw, throws and finally. Generally, try is used to execute a program. If an exception occurs, the system will throw an exception. At this time, you can catch it by its type, or finally handle it by the default processor.

Use try to specify a program to prevent all "exceptions". Immediately after the try program, you should include a catch clause to specify the type of "exception" you want to catch. The throw statement is used to explicitly throw an "exception".

Throws is used to indicate various "exceptions" that may be thrown by a member function.

Finally, to ensure that a piece of code is executed no matter what "exception" occurs.

You can write a try statement outside a member function call and another try statement inside the member function to protect other code. Whenever a try statement is encountered, the "exception" frame is placed on the stack until all the try statements are completed. If the next level try statement does not handle an "exception", the stack will expand until a try statement handling such an "exception" is encountered.

97. Can multiple classes (not internal classes) be included in a ". Java" source file? What are the restrictions?

sure. Only one class name must be the same as the file name.

98. What technologies do all parts of MVC have to be implemented? How?

MVC is short for model view controller. "Model" represents the business logic of the application (implemented through JavaBeans and EJB components), "view" is the presentation surface of the application (generated by JSP pages), and "controller" provides the processing process control of the application (usually a servlet), through this design model, the application logic, processing process and display logic are divided into different components, which can be interacted and reused.

99. How many methods can you implement a thread in Java? What keywords are used to modify the synchronization method? Why are the stop () and suspend () methods not recommended?

There are two implementation methods: Inheriting thread class and implementing runnable interface

Modify synchronization method with synchronized keyword

Stop () is deprecated because it is unsafe. It unlocks all locks acquired by threads, and if objects are in an incoherent state, other threads can check and modify them in that state. As a result, it is difficult to detect the real problem. The suspend () method is prone to deadlock. When suspend () is called, the target thread stops, but still holds the lock obtained before. At this time, no other thread can access the locked resource unless the "suspended" thread resumes running. For any thread, if they want to recover the target thread and try to use any locked resource, it will cause deadlock. Therefore, instead of using suspend (), you should put a flag in your thread class to indicate whether the thread should be active or suspended. If flag indicates that thread should be suspended, it is ordered to enter wait state with the wait (). If flag indicates that thread should resume, restart thread with the a notify().

100. How many types of streams are there in Java? JDK provides some abstract classes for each type of stream to inherit. Please tell me which classes they are respectively? Byte stream, character stream. Byte stream inherits from InputStream OutputStream, character stream inherits from inputstreamreader outputstreamwriter. In Java There are many other streams in the IO package, mainly to improve performance and ease of use.

101. Is there a memory leak in Java? Please briefly describe it.

meeting. For example: int i, I2; return (i-i2); // When I is a positive number large enough and I2 is a negative number large enough. The result is an overflow and an error.

102. What is the mechanism for realizing polymorphism in Java?

Overriding and overloading of methods are different manifestations of Java polymorphism. Overriding is a manifestation of polymorphism between parent and child classes, and overloading is a manifestation of polymorphism in a class.

103. What is the basic principle of garbage collector? Can the garbage collector reclaim memory right away? Is there any way to actively notify the virtual machine for garbage collection? For GC, when the programmer creates an object, GC starts to monitor the address, size and usage of the object. Generally, GC records and manages all objects in the heap in the form of directed graph. In this way, you can determine which objects are "reachable" and which objects are "unreachable". When the GC determines that some objects are "unreachable", the GC is responsible for reclaiming these memory spaces. sure. Programmers can manually execute system GC () tells GC to run, but the Java language specification does not guarantee that GC will execute.

104. What is the difference between static variables and instance variables?

static i = 10; // Constant class A; a.i =10;// variable

105. What is java serialization and how to implement Java serialization?

Serialization is a mechanism used to process object stream. The so-called object stream is to stream the content of the object. You can read and write the streamed objects, or transfer the streamed objects between networks. Serialization is to solve the problem caused by reading and writing to the object stream. Implementation of serialization: implement the serializable interface for the class to be serialized. The interface has no methods to be implemented. Implements serializable is just to mark that the object can be serialized, and then use an output stream (such as fileoutputstream) to construct an objectoutputstream object. Then, Using the writeobject (object obj) method of the objectoutputstream object, you can write out the object with the parameter obj (that is, save its state). To restore, use the input stream.

106. Can I call a non static method from within a static method?

No, if it contains the method () of the object; Object initialization cannot be guaranteed

107. When writing the clone () method, there is usually a line of code. What is it?

Clone has a default behavior, super clone(); He is responsible for generating the correct size of space and copying it bit by bit.

108. How to jump out of the current multiple nested loop in Java?

Use break; Return method.

109. What are the characteristics of the list, map and set interfaces when accessing elements?

List holds elements in a specific order, and there can be duplicate elements. Set cannot have duplicate elements, internal sort. Map saves the key value value, which can be multiple values.

110. What is J2EE?

J2EE is a multi-layered, distributed, component-base based enterprise application model proposed by Sun company In such an application system, it can be divided into different components according to functions, and these components can be on different computers and in corresponding tiers. The hierarchy includes client tier components, web tier and components, business tier and components, and enterprise information system (EIS) layer.

111. UML

Standard modeling language UML. Use case diagram, static diagram (including class diagram, object diagram and package diagram), behavior diagram, interaction diagram (sequence diagram, cooperation diagram), implementation diagram.

112. Name some commonly used classes, packages and interfaces. Please give five each

Common classes: BufferedReader bufferedwriter FileReader filewirter string integer

Common packages: Java lang java. awt java. io java. util java. sql

Common interface: remote list map document NodeList

113. What design patterns are used in the development? For what occasion?

Each pattern describes an emerging problem in our environment, and then describes the core of the solution to the problem. In this way, you can use those existing solutions countless times without repeating the same work. It mainly uses the design pattern of MVC. Used to develop JSP / servlet or J2EE related applications. Simple factory mode, etc.

114. What actions does JSP have? What are the functions?

JSP has the following six basic actions: JSP: include: introduce a file when the page is requested. Jsp: usebean: find or instantiate a JavaBean. Jsp: setproperty: sets the properties of a JavaBean. Jsp: getproperty: output the properties of a JavaBean. Jsp: forward: forward the request to a new page. Jsp: plugin: generate object or embed tags for Java plug-ins according to browser type.

115. Can anonymous inner class extend other classes and implement interface?

You can inherit other classes or complete other interfaces, which is commonly used in swing programming.

116. What is the difference between application server and web server?

Application server: Weblogic, Tomcat, JBoss

WEB SERVER:IIS、 Apache

117. Relationship and difference between BS and CS.

C / S is the abbreviation of client / server. The server usually adopts high-performance PC, workstation or minicomputer, and adopts large database system, such as Oracle, Sybase, Informix or SQL server. The client needs to install special client software. B / S is the abbreviation of browser / server, Only one browser is installed on the client (browser), such as Netscape Navigator or Internet Explorer. The server installs databases such as Oracle, Sybase, Informix or SQL server. Under this structure, the user interface is completely realized through the WWW browser, and some transaction logic is realized at the front end, but the main transaction logic is realized at the server end. The browser interacts with the database through the web server.

Difference between C / s and B / s:

1. Different hardware environments:

C / S is generally built on a dedicated network, a small-scale network environment, and LAN provides connection and data exchange services through special servers

B / S is built on the WAN and does not need to be a special network hardware environment, such as telephone Internet access and renting equipment Information management It has a stronger adaptability than C / s. generally, it only needs an operating system and a browser

2. Different safety requirements

C / S is generally oriented to relatively fixed user groups and has strong control over information security C / S structure is suitable for general highly confidential information system Some publicly available information can be released through B / s

B / S is built on the wide area network, and its security control ability is relatively weak. It may face unknown users.

3. Different program architectures

C / s program can pay more attention to process, multi-level verification of authority and less consideration of system running speed

B / S's multiple considerations of security and access speed are based on the need for more optimization There are higher requirements than C / s. The program architecture of B / S structure is the development trend from Ms Net series, such as BizTalk 2000 and Exchange 2000, fully support the system built by network components JavaBean component technology pushed by sun and IBM makes B / s more mature

4. Different software reuse

C / s program can inevitably consider the integrity, and the reusability of components is not as good as that of components under the requirements of B / s

The multiple structures of B / s pairs require relatively independent functions of components It can be reused relatively well Just buy a table and reuse it instead of a stone table on the wall

5. Different system maintenance

Due to the integrity of C / s program, it is necessary to investigate and deal with the problems and system upgrade It's hard to upgrade Maybe it's a new system

B / s component composition and individual replacement of components to realize seamless upgrading of the system Minimize system maintenance overhead Users can upgrade by downloading and installing from the Internet

6. Dealing with different problems

C / s program can handle the fixed user surface, and in the same area, it has high security requirements and is related to the operating system It should all be the same system

B / S is built on WAN, facing different user groups and scattered regions, which C / s can't do Minimal relationship with operating system platform

7. Different user interfaces

C / S is mostly built on the window platform, with limited performance methods and high requirements for programmers

B / S is built on the browser, which has a richer and more vivid way to communicate with users And most of the difficulty is reduced and the development cost is reduced

8. Different information flows

C / s program is generally a typical centralized mechanical processing, with relatively low interactivity

The flow direction of B / s information can be changed. The change of B-B, B-C, B-G and other information and flow direction is more like a trading center.

118. Explanation of thread and GDI class under Linux.

Linux implements the "one-to-one" thread model based on the core lightweight process. A thread entity corresponds to a core lightweight process, and the management between threads is realized in the function library outside the core. GDI class is the image device programming interface class library.

119. Application of struts (such as struts Architecture)

Struts is an open source framework for developing web applications using java servlet / JavaServer pages technology. Using struts, an application architecture based on MVC (model view controller) design pattern can be developed. Struts has the following main functions: 1 It contains a controller servlet that can send the user's request to the corresponding action object. II JSP free tag library, and provides association support in the controller servlet to help developers create interactive form applications. III It provides a series of practical objects: XML processing, automatic processing of JavaBeans properties through java reflection APIs, internationalization tips and messages.

120. What is JDO?

JDO is a new specification for Java object persistence, short for Java data object. It is also a standardized API for accessing objects in a data warehouse. JDO provides transparent object storage, so for developers, Storing data objects does not require additional code at all (such as the use of JDBC API). These cumbersome routine tasks have been transferred to JDO product providers, freeing developers to focus their time and energy on business logic. In addition, JDO is flexible because it can run on the bottom of any data. JDBC is only oriented to relational database (RDBMS) JDO is more general and provides storage functions to any underlying data, such as relational database, file, XML and object database (ODBMS), which makes the application more portable.

121. Can an internal class reference the members of its containing class? Are there any restrictions?

An internal class object can access the contents of the external class object that created it

122. Explanation of web service terms. Introduction to jswdl development kit. Explanation of jaxp and JAXM. Soap, UDDI, WSDL interpretation.

Web ServiceWeb service is a network-based, distributed modular component. It performs specific tasks and complies with specific technical specifications. These specifications enable Web service to interoperate with other compatible components.

Jaxp (Java API for XML parsing) defines a general interface for using Dom and XSLT in Java. In this way, you only need to use these general interfaces in your program, and you don't need to modify the code when you need to change the specific implementation.

JAXM (Java API for XML messaging) is an API that provides access methods and transmission mechanisms for soap communication.

WSDL is an XML format used to describe a network service as a set of endpoints that operate on messages containing document oriented information or process oriented information. This format first describes the operation and message abstractly, and then binds it to the specific network protocol and message format to define the endpoint. The relevant concrete endpoints are combined into abstract endpoints (services).

Soap is simple object access protocol, which is a lightweight protocol for exchanging XML encoded information.

The purpose of UDDI is to establish standards for e-commerce; UDDI is a set of implementation standards for web-based, distributed, information registry provided for web services. At the same time, it also includes a set of implementation standards for access protocols that enable enterprises to register their own web services so that other enterprises can discover.

Java code error checking

one

Heroes, what's wrong with this?

Answer: wrong. Abstract method must end with a semicolon without curly braces.

two

Is there anything wrong?

Answer: wrong. No access modifiers (private, public, and protected) can be placed before local variables. Final can be used to modify local variables

(final, like abstract and strictfp, are non access modifiers. Strictfp can only modify classes and methods, not variables).

three

Doesn't that seem to be wrong?

Answer: wrong. Abstract methods cannot be decorated with private. The methods of abstract are to let the subclass implement specific details. How can we use private to implement abstract

Method is blocked? (similarly, final cannot be added before abstract method).

four

This is obvious.

Answer: wrong. Int x is modified to final, which means that x cannot be modified in addone method.

five

Similar to the above, they are all about final. Is this wrong?

Answer: correct. In addone method, the parameter o is modified to final. If we modify the reference of O in addone method

(for example: o = new other();), Then, as in the previous example, this question is also wrong. However, the member vairable of O is modified here

(member variable), and O's reference has not changed.

six

What's wrong? I can't see it.

Answer: correct. The output is "I = 0". Int i belongs to instant variable (instance variable, or member variable). Instant variable has default value. The default value of int is 0.

seven

There is only one difference from the above question, that is, there is one more final. Is that wrong?

Answer: wrong. Final int i is a final instant variable (instance variable, or member variable). The final instant variable has no default value and must be given an explicit value before the end of the constructor. It can be modified to "final int i = 0;".

eight

It looks perfect.

Answer: wrong. It seems that there is no problem calling dosomething in main. After all, both methods are in the same class. But look closely, main is static. Static methods cannot directly call non static methods. It can be changed to "system. Out. Println (" s.dosomething() returns "+ s.dosomething());". Similarly, static method cannot access non static instant variable.

nine

Here, the file of something class is called otherthing java

This seems obvious.

Answer: correct. No one has ever said that Java's class name must be the same as its file name. However, the name of public class must be the same as the file name.

10.

Answer: wrong. Errors will occur during compilation (different JVMs with different error descriptions have different information, which means that x is not explicitly called, and both X match (just like directly declaring date when importing java.util and java.sql packages at the same time). For the variables of the parent class, super. X can be used to specify, and the attribute of the interface is implied as public static final by default. Therefore, a.x can be used to specify.

eleven

This mistake is not easy to find.

Answer: wrong. "Interface rollable extensions playable, bounceable" is OK. Interface can inherit multiple interfaces, so that's right here. The problem is "ball ball = new ball (" pingpang ");" in the interface rollable. Any interface variable (interface variable, also known as member variable) declared in the interface is public static final by default. That is, "ball ball = new ball (" pingpang ");" In fact, it is "public static final ball = new ball (" pingpang ");". In the play () method of the ball class, "ball = new ball (" football ");" The reference of the ball is changed, and the ball here comes from the rollable interface. The ball in the rollable interface is public static final, and the reference of the final object cannot be changed. Therefore, the compiler will be in "ball = new ball (" football ");" There are errors displayed here.

Java programming problem

1. Now enter n numbers separated by commas; Then you can select ascending or descending sorting; Press the submit key to display the sorting on another page. The result is reset

2. Amount conversion: the amount in Arabic numerals is converted into the traditional Chinese form, such as: (¥ 1011) - > (one thousand and eleven yuan only) output.

3. The execution order of classes during inheritance is usually a multiple-choice question. What will you print out?

Answer: parent class:

Subclass:

Output results:

C:>java test. ChildClass FatherClass Create FatherClass Create ChildClass Create

4. Implementation of internal classes?

A: the example code is as follows:

Output results:

The description is as follows:

I Static inner classes can have static members, while non static inner classes cannot have static members. So a and B are wrong

II The non static members of the static inner class can access the static variables of the external class, but not the non static variables of the external class; Return D1 error. So D is wrong

III Non static members of a non static inner class can access non static variables of an outer class. So C is correct

IV The answers are C and E

5. Java Communication programming, programming questions (or Q & A), programming with java socket, reading a few characters of the server, and then writing to the local display?

Answer: server side program:

Java interview questions and partial answers of a company (more difficult)

1。 Please briefly describe the difference between vector and ArrayList, and the difference between hashtable and HashMap. (5)

2。 Under what circumstances would you use serializability in your Java code? (5) Why do objects placed in httpsession have to be serializable? (5)

3。 Why do you have to override the hashcode () method after overriding the equals () method? (10)

4。 What's the difference between sleep () and wait ()? (10)

5。 Programming question: how much is 2 multiplied by 17 calculated by the most efficient method? (5)

6。 Is java free of memory leaks? Look at the code snippet below and point out the hidden problems of these codes. (10)

7。 Please explain your understanding of the concept of "lock" in Java multithreading. (10)

8。 All recursive implementations can be implemented in a circular way. Please describe the advantages and disadvantages of these two implementations.

Examples are given to illustrate when recursion can be used, and when only loops can be used instead of recursion? (5)

9。 Please briefly talk about your understanding of Test Driven Development (TDD). (10)

10。 Please explain your understanding of "interface oriented programming". (10)

11。 There is a concept of "container" in J2EE. EJB, Pico and spring all have them

The containers implemented by each container and the components managed by the container will have the characteristics of life cycle. Excuse me, why do you need a container?

What are its benefits? What problems will it bring? (15)

12。 Please explain your understanding of IOC (inversion of control). (take pic and spring IOC as examples to illustrate their respective characteristics in Implementation) (10)

13。 The following code runs normally most of the time. Under what circumstances will problems occur? Where is the root of the problem? (10)

answer:

。 Please briefly describe the difference between vector and ArrayList, and the difference between hashtable and HashMap. (5) Thread safe or not

2。 Under what circumstances would you use serializability in your Java code? (5) Why must the objects placed in httpsession be serializable for session replication and cache persist and reload in cluster? (5) No, but the session deserialization process will make the object unavailable

3。 Why do you have to override the hashcode () method after overriding the equals () method? (10) API specification

4。 What's the difference between sleep () and wait ()? (10) The former occupies CPU and the latter is idle CPU

5。 Programming question: how much is 2 multiplied by 17 calculated by the most efficient method? (5)17>>1

6。 Is java free of memory leaks? Look at the code snippet below and point out the hidden problems of these codes. (10) Not No memory leaks were found

7。 Please explain your understanding of the concept of "lock" in Java multithreading. (10) Synchronization factor: if a synchronization factor is added to a piece of code, only one thread can execute this section in the whole JVM, and the other threads wait for execution in FIFO mode

8。 All recursive implementations can be implemented in a circular way. Please describe the advantages and disadvantages of these two implementations.

Examples are given to illustrate when recursion can be used, and when only loops can be used instead of recursion? (5) I didn't find that all recursion can be realized by loop, especially the recursive algorithm that doesn't know the multiplicity of loop The advantage of recursion is simplicity and good abstraction; The loop is more intuitive Recursion is generally used to handle operations that can be transformed into simpler secondary transactions It cannot be used in cases where Level 2 transactions cannot be summarized or where Level 2 transactions are more complex

9。 Please briefly talk about your understanding of Test Driven Development (TDD). (10) No

10。 Please explain your understanding of "interface oriented programming". (10) 1. Conducive to expansion; 2. Methods with less exposure;

11。 There is a concept of "container" in J2EE. EJB, Pico and spring all have them

The containers implemented by each container and the components managed by the container will have the characteristics of life cycle. Excuse me, why do you need a container?

What are its benefits? What problems will it bring? (15) Componentization, framework design

12。 Please explain your understanding of IOC (inversion of control). (you can take pic and spring IOC as examples to illustrate their respective characteristics in Implementation) (10) don't understand

13。 The following code runs normally most of the time. Under what circumstances will problems occur? Where is the root of the problem? (10) The use purpose of wait and notify cannot be achieved. The obj of wait() cannot notify() The author did not understand the wait and notify mechanisms

How many points did you get?

1。 Please briefly describe the difference between vector and ArrayList, and the difference between hashtable and HashMap. (5)

// thread-safe or unsafe,Could contain null values or not

2。 Under what circumstances would you use serializability in your Java code? (5)

Why do objects placed in httpsession have to be serializable? (5)

// save,communicate

3。 Why do you have to override the hashcode () method after overriding the equals () method? (10)

// implementations of dictionaries need hashCode() and equals()

4。 What's the difference between sleep () and wait ()? (10)

// threads communication: wait() and notifyAll()

5。 Programming question: how much is 2 multiplied by 17 calculated by the most efficient method? (5)

// 2<<4+2

6。 Is java free of memory leaks? Look at the code snippet below and point out the hidden problems of these codes. (10) ...

7。 Please explain your understanding of the concept of "lock" in Java multithreading. (10)

// optimistic lock,pessimistic lock,signal,dead lock,starvation,synchronization

8。 All recursive implementations can be implemented in a circular way. Please describe the advantages and disadvantages of these two implementations.

Examples are given to illustrate when recursion can be used, and when only loops can be used instead of recursion? (5)

// recursive: when you need a stack and stack memory is enough // non-recursive: when you need a queue

9。 Please briefly talk about your understanding of Test Driven Development (TDD). (10)

// write unit testing code first

10。 Please explain your understanding of "interface oriented programming". (10)

// adapter,listener,bridge,decorator,proxy... patterns

11。 There is a concept of "container" in J2EE. EJB, Pico and spring all have them

The containers implemented by each container and the components managed by the container will have the characteristics of life cycle. Excuse me, why do you need a container?

What are its benefits? What problems will it bring? (15)

// encapsulation

12。 Please explain your understanding of IOC (inversion of control). (take pic and spring IOC as examples to illustrate their respective characteristics in Implementation) (10)

// reduce classes' dependencies

13。 The following code runs normally most of the time. Under what circumstances will problems occur? Where is the root of the problem? (10)

The above is a collection of Java interview questions and answers (122 basic questions and 19 code questions) introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>