Java written test 100 questions (1-50)

Source: Internet
Author: User
Tags websphere application server

Java Basics
1. What are the features of object orientation?
1. Abstraction:
Abstraction is to ignore those aspects irrelevant to the current target in a topic, so that you can pay more attention to the aspects related to the current target. Abstraction is not intended to understand all the problems, but to select a part of the problem. Abstract: Process abstraction and data abstraction.
2. Inheritance:
Inheritance is a hierarchical model that connects classes and allows reuse of encouraging 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 features 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 ). 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. encapsulation:
Encapsulation is to enclose the process and data. Data access can only be performed through the defined interface. Object-oriented computing begins with the basic concept that the real world can be depicted as a series of completely autonomous and encapsulated objects that access other objects through a protected interface.
4. Polymorphism:
Polymorphism allows different types of objects to respond to the same message. Polymorphism includes parameterized polymorphism and inclusion polymorphism. The polymorphism language has the advantages of flexibility, abstraction, behavior sharing, and code sharing, which effectively solves the same name problem of application functions.
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 the final type. Therefore, it cannot be inherited or modified. 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: The reference type and the original type (or the built-in type ). Int Is the original data type of Java, and integer is the encapsulation class provided by Java for int. Java provides encapsulation classes for each original type.
Original Type encapsulation class
Booleanboolean
Charcharacter
Bytebyte
Shortshort
Intinteger
Longlong
Floatfloat
Doubledouble
The behavior of the reference type and the original type is completely different, and they have different semantics. The reference type and the original type have different features and usage, they include: size and speed problems, which type of data structure is stored, the default value specified when the reference type and original type are used as instance data of a class. The default value of the instance variables referenced by the object is null, and the default value of the original type of instance variables is related to their types.
4. Differences between string and stringbuffer
The Java platform provides two classes: string and stringbuffer, which can store and operate strings, that is, character data containing multiple characters. This string class provides a string whose values cannot be changed. The stringbuffer class provides strings for modification. You can use stringbuffer when you know that character data is changing. 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 indicates an abnormal state that may occur during the running of the program. An exception indicates an exception that may occur during common operations on the virtual machine. It is a common running error. The Java compiler requires that methods must declare and throw possible non-runtime exceptions, but do not require that they throw uncaptured runtime exceptions.
6. Tell the servlet lifecycle and the difference between Servlet and CGI.
After the servlet is instantiated by the server, the container runs its init method, runs its service method when the request arrives, and the service method automatically dispatches the doxxx method (doget, dopost) corresponding to the request, etc, the destroy method is called when the server decides to destroy the instance.
The difference with CGI is that the servlet is in a server process and runs its service method in multi-thread mode. An instance can serve multiple requests, and its instance is generally not destroyed, CGI generates a new process for each request. After the service is completed, it is destroyed, so the efficiency is lower than that of servlet.
7. Specify the storage performance and features of arraylist, vector, and sorted list.
Both arraylist and vector use arrays to store data. The number of elements in the array is greater than that in the actual data storage to add and insert elements. They allow the element to be indexed by serial number directly, however, inserting elements involves memory operations such as array element movement, so index data is fast and data insertion is slow. Because vector uses the Synchronized Method (thread-safe), its performance is generally inferior to that of arraylist, the sorted list uses a two-way linked list for storage. Data indexed by serial number needs to be traversed in the forward or backward direction. However, when inserting data, you only need to record the items before and after this item, so the insertion speed is fast.
8. What technologies are EJB implemented based on? And 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 technologies such as JNDI, RMI, and JAT.
Sessionbean is used in J2EE applications to perform some server-side business operations, such as accessing the 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, entitybean is a persistent object that represents an object view of an object stored in persistent storage or an entity implemented by an existing enterprise application.
Session Bean can be further subdivided into stateful Session Bean and stateless Session Bean. Both session beans can execute the system logic in method, the difference is that the stateful session bean can record the caller's status. Therefore, a user usually has a corresponding stateful Session Bean entity. Although stateless Session Bean is also a logical component, it is not responsible for recording the user status, that is, when the user calls stateless
When Session Bean is used, EJB container does not find the entity of the specific stateless Session Bean to execute this method. In other words, when several users execute a stateless Session Bean's methods, they will execute the same bean instance. In terms of memory, compared with stateful Session Bean and stateless Session Bean, stateful Session Bean consumes J2EE Server
Large memory, but stateful Session Bean has the advantage that it can maintain the user's status.
9. Differences between collection and collections.
Collection is the upper-level interface of the Collection class. Its inherited interfaces include set and list.
Collections is a help class for collection classes. It provides a series of static methods for searching, sorting, thread security, and other operations on various sets.
10. Difference Between & and.
& Is a bitwise operator that represents bitwise and operation, & is a logical operator that represents logic and (and ).
11. Differences 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 key values ), because of non-thread security, the efficiency may be higher than that of hashtable.
Hashmap allows null as the key or value of an entry, whereas hashtable does not.
Hashmap removes the contains method of hashtable and changes it to containsvalue and containskey. The contains method is easy to misunderstand.
Hashtable inherits from the dictionary class, while hashmap is an implementation of the map interface introduced by java1.2.
The biggest difference is that the hashtable method is synchronize, but hashmap is not. When multiple threads access hashtable, they do not need to implement synchronization for their own methods, hashmap must provide external synchronization for it.
The hash/rehash algorithms used by hashtable and hashmap are roughly the same, so there is no big difference in performance.
12. Differences between final, finally, and finalize.
Final is used to declare attributes. Methods and classes indicate that attributes are unchangeable, methods cannot be overwritten, and classes cannot be inherited.
Finally is a part of the structure of the exception handling statement, indicating that it is always executed.
Finalize is a method of the object class. This method is called when the garbage collector is executed. It can overwrite this method to collect other resources during garbage collection, for example, close a file.
13. What is the difference between sleep () and wait?
Sleep is a thread method, which causes the thread to suspend the execution for a specified time and give the execution opportunity to other threads. However, the monitoring status remains unchanged and will be automatically restored after the time. Calling sleep does not release the object lock.
Wait is an object-class method. Calling the wait method for this object causes this thread to discard the object lock and enter the waiting lock pool for this object. Only the notify method (or notifyall) is issued for this object) then this thread enters the object lock pool and prepares to get the object lock and enters the running state.
14. Differences between overload and override. Can the overloaded method change the type of the returned value?
Overriding and overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the Child class, and overloading is a manifestation of the polymorphism in a class. If a subclass defines a method with the same name and parameter as its parent class, we say this method is overwritten ). When a subclass object uses this method, the definition in the subclass is called. For it, the definition in the parent class is "blocked. If multiple methods with the same name are defined in a class, they may have different numbers of parameters or different parameter types, it is called overloading ). The overloaded method can change the type of the returned value.
15. What is the difference between error and exception?
Error indicates that recovery is not a serious problem that is impossible but difficult. For example, memory overflow. It is impossible to expect the program to handle such a situation.
Exception indicates a design or implementation problem. That is to say, it indicates that if the program runs normally, it will never happen.
16. What are the similarities and differences between synchronization and Asynchronization? Under what circumstances should they be used separately? Examples.
If data is shared among threads. For example, if the data being written may be read by another thread or the data being read may have been written by another thread, the data is shared 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, adopting asynchronous channels is often more efficient.
17. What is the difference between abstract class and interface?
The class that declares a method rather than implementing it is called abstract class. It is used to create a class that reflects some basic behaviors and declare a method for this class, however, this class cannot be implemented in this class. You cannot create an abstract instance. However, you can create a variable whose type is an abstract class and point it to an instance of a specific subclass. Abstract constructors or abstract static methods are not allowed. The subclasses of abstract classes provide implementation for all abstract methods in their parent classes. Otherwise, they are also abstract classes. Instead, implement this method in the subclass. Other classes that know their behavior can implement these methods in the class.
An interface is a variant of an abstract class. All methods in the interface are abstract. Multi-inheritance can be achieved by implementing such an interface. All methods in the interface are abstract, and none of them have a program body. The interface can only define static final member variables. The implementation of an interface is similar to that of a subclass, except that the implementation class cannot inherit behaviors from the interface definition. When a class implements a special interface, it defines (to be given by the program body) all the methods of this interface. Then, it can call the interface method on any object that implements the interface class. Because there is an abstract class, it allows the interface name as the type of the referenced variable. Normally, dynamic Association editing will take effect. The reference can be converted to the interface type or from the interface type conversion, instanceof
The operator can be used to determine whether an object's class implements an interface.
18. What is the difference between heap and stack.
Stack is a linear set. The operations for adding and deleting elements should be completed in the same segment. The stack is processed as follows.
Heap is an element of stack.
19. Differences between forward and redirect
Forward is a server request resource. 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 does not 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 based on logic to tell the browser to request the address again. Generally, the browser will re-request the address 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 Bean is a reusable component and there is no strict specification for Java Bean. Theoretically, any Java class can be a bean. However, since Java Beans are created by containers (such as Tomcat), Java Beans should have a constructor without parameters. In addition, generally, Java Bean must implement the serializable interface to realize bean persistence. Java Bean is actually equivalent to the COM component in the local process in the Microsoft COM model. It cannot be accessed across processes. Enterprise Java Bean is equivalent to DCOM, which is a distributed component. It is based on Java remote method call (RMI) technology, so EJB can be remotely accessed (cross-process, cross-computer ). However, EJB must be deployed in containers such as webspere and weblogic. The EJB client never directly accesses the real EJB component but accesses it through its container. The EJB container is the proxy of the EJB component. The EJB component is created and managed by the container. The customer 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 as static. It can be instantiated without relying on external class instances. In general, internal classes must be instantiated before they can be instantiated.
22. What is the difference between dynamic include and static include in JSP?
Dynamic include is implemented using JSP: include action <JSP: Include page = "embedded ded. JSP "Flush =" true "/> always checks for changes in the contained files. It is suitable for inclusion of dynamic pages and can contain parameters.
Static include is implemented using the include pseudo code, and changes to the included files are not checked. This applies to static pages containing <% @ include file = "included.htm" %>
23. When to use assert.
Assertion is a common debugging method in software development. Many development languages support this mechanism. In implementation, assertion is a statement in the program. It checks a Boolean expression. A correct program must ensure that the value of this Boolean expression is true. If this value is false, if the program is in an incorrect state, the system will give a warning or exit. Generally, assertion is used to ensure the most basic and critical correctness of the program. The assertion check is usually enabled during development and testing. To improve performance, the assertion check is usually disabled after the software is released.
24. What is GC? Why does GC exist?
GC is the meaning of garbage collection (gabage collection). Memory Processing is a place where programmers are prone to problems. Forgetting or wrong memory collection can lead to instability or even crash of programs or systems, the GC function provided by Java can automatically monitor whether the object exceeded the scope to automatically recycle the memory. the Java language does not provide a display operation to release the allocated memory.
25. Short S1 = 1; S1 = S1 + 1; what is the error? Short S1 = 1; S1 + = 1; what is the error?
Short S1 = 1; S1 = S1 + 1; (the S1 + 1 operation results in int type, which requires forced conversion)
Short S1 = 1; S1 + = 1; (it can be compiled correctly)
26. How much is math. Round (11.5? Math. Round (-11.5) and so on?
Math. Round (11.5) = 12
Math. Round (-11.5) =-11
The round method returns a long integer closest to the parameter. After the parameter is added to 1/2, the floor is obtained.
27. How many string objects are created in string S = new string ("XYZ?
Two
28. Design four threads, two of which increase 1 to J each time, and the other two reduce 1 to J each time. Write the program.
The following programs use internal classes to implement threads, and do not consider the sequence when J is added or subtracted.
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 ++ ){
Dec ();
}
}
}
}
29. Is there a goto in Java?
Reserved Words in Java, which are not currently used in Java.
30. Do I use run () or start () to start a thread ()?
When a thread is started, the START () method is called to make the virtual processor represented by the thread in a running state, which means that it can be scheduled and executed by JVM. This does not mean that the thread will run immediately. The run () method can generate the exit sign to stop a thread.

31. EJB includes (sessionbean, entitybean) indicating their lifecycle and how to manage transactions?
Sessionbean: the lifecycle of stateless Session Bean is determined by the container. When the client sends a request to create a bean instance, the EJB container does not have to create a new bean instance for the client to call. Instead, it finds an existing instance and provides 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 on the server and associate it with the client, when this client calls the stateful Session Bean method later, the container will dispatch the call to the bean instance associated with this client.
Entitybean: entity beans can survive for a relatively long time, And the status is continuous. As long as the data in the database exists, entity beans will survive. It is not based on the application or service process. Even if the EJB container crashes, entity beans survive. Entity beans can be managed by containers or beans themselves.
EJB uses the following technical management practices: ots of Object Management Organization (OMG), Transaction Service (JTs) of Sun Microsystems, and Java transaction API (JTA ), the Xa interface of the 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, cmexception, concurrentmodificationexception, domexception, emptystackexception, fatal,
Illegalmonitorstateexception, illegalpathstateexception, illegalstateexception, imagingopexception, exception, missingresourceexception, exception, nosuchelementexception, nullpointerexception, profiledataexception, providerexception,
Rasterformatexception, securityexception, systemexception, undeclaredthrowableexception, unmodifiablesetexception, unsupportedoperationexception
34. CAN interfaces be inherited? Can an abstract class implement the (implements) interface? Can an abstract class inherit a concrete class )?
Interfaces can inherit interfaces. Abstract classes can be implemented (implements) interfaces, and whether abstract classes can inherit object classes, provided that object classes must have clear constructors.
35. Does list, set, and map inherit from the collection interface?
List, set is, map is not
36. What is the working mechanism of the data connection pool?
When the J2EE server is started, a certain number of pool connections will be established, and a certain number of pool connections will be maintained. When the client program needs to connect, the pool driver returns an unused pool connection and logs its table as busy. If no idle connection exists, the pool driver creates a certain number of connections. The number of new connections is determined by the configuration parameters. When the pool connection call is completed, the pool driver records the connection table as idle, and other calls can use the connection.
37. can abstract methods be both static, native, and synchronized?
None
38. Does the array have the length () method? Does string have the length () method?
The array does not have the length () method. It has the Length attribute. String has the length () method.
39. The elements in the set cannot be repeated. How can we identify whether the elements are repeated or not? Is = or equals () used ()? What are their differences?
The elements in the set cannot be repeated, so the iterator () method is used to identify whether the elements are repeated or not. Equals () is used 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, in order to return the true value when the content and type of the two separated objects match.
40. Can constructor be overwritten?
Constructor cannot be inherited, so overriding cannot be overwritten, but overloading can be overloaded.
41. Can I inherit the string class?
The string class is a final class, so it cannot be inherited.
42. Does swtich work 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. Long and string cannot apply to swtich.
43. If there is a return statement in try {}, will the code in finally {} following this try be executed? When will it be executed, before or after return?
Will be executed, before return.
44. Programming question: how many equals 2x8 in the most efficient way?
2 <3
45. The values of the two objects are the same (X. Equals (y) = true), but different hash codes are available, right?
No. It has the same hash code.
46. After an object is passed as a parameter to a method, this method can change the attributes of this object and return the changed result, so is it a value transfer or a reference transfer?
Is the value transfer. Java programming language only supports value passing parameters. When an object instance is passed as a parameter to a method, the parameter value is a reference to the object. The object content can be changed in the called method, but the object reference will never change.
47. After a thread enters a synchronized method of an object, can other threads access other methods of this object?
No. One Synchronized Method of an object can only be accessed by one thread.
48. Programming question: Write a singleton.
The Singleton mode ensures that only one instance of a class exists in a Java application.
The Singleton mode generally has several forms:
The first form: defines a class. Its constructor is private. It has a static private class variable. When the class is initialized, use a public getinstance method to obtain its reference, and then call the method.
Public class Singleton {
Private Singleton (){}
// Define your own instance internally. Isn't it strange?
// Note that this is private for internal calls only
Private Static Singleton instance = new Singleton ();
// Here is a static method for external access to this class, which can be accessed directly.
Public static Singleton getinstance (){
Return instance;
}
}
Second form:
Public class Singleton {
Private Static Singleton instance = NULL;
Public static synchronized Singleton getinstance (){
// This method is better than above. You don't need to generate objects every time. It's just the first time.
// Generate instances during use, improving efficiency!
If (instance = NULL)
Instance = new Singleton ();
Return instance ;}
}
Other forms:
Defines a class. Its constructor is private and all methods are static.
It is generally considered that the first form is more secure.
49. The similarities and differences between Java interfaces and C ++ virtual classes.
Because Java does not support multi-inheritance, it is possible that a class or object must use methods or attributes in several classes or objects respectively. The existing single Inheritance Mechanism cannot meet the requirements. Compared with inheritance, interfaces are more flexible because they do not have any implementation code. After a class implements an interface, this class implements all the methods and attributes in the interface, and the attributes in the interface are under the default state are public static, and all methods are public by default. A class can implement multiple interfaces.
50. Simple Principle and Application of the Exception Handling Mechanism in Java.
When a Java program violates the Java Semantic Rules, the Java Virtual Machine will indicate an error as an exception. There are two types of violation of Semantic Rules. One is the built-in semantic check of the Java class library. For example, if the array subscript is out of the range, indexoutofboundsexception is triggered. When a null object is accessed, nullpointerexception is thrown. Another scenario is that Java allows programmers to extend this semantic check. programmers can create their own exceptions and choose when to use the throw keyword to cause exceptions. All exceptions are subclasses of Java. Lang. thowable.

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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