Java learning experience (1)

Source: Internet
Author: User
Tags switch case

1. Does the array have the length () method? Does string have the length () method?

A: The array does not have the length () method. It has the Length attribute.

String has the length () method.

2. String S = new string ("XYZ"); how many string objects are created?

A: There are two objects, one being "xyx" and the other being the reference object s pointing to "xyx.

3. What is the difference between abstract class and interface?

A: The class that declares the existence of a method without 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. The instanceof operator can be used to determine whether the class of an object implements the interface.

4. = what is the difference between equals and equals?

A: = used to determine whether two referenced variables point to the same object instance.

Equals is used to determine whether two values are equal.

5. 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?

A: The elements in the set cannot be repeated. Use the iterator () method 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.

6. Differences between interfaces and abstract classes

A: Non-abstract methods in abstract classes can be overwritten by the quilt class, but all methods in the interface must be implemented by the quilt class.

An abstract class and a subclass have a parent-child relationship, for example, a is B, but there is no obvious parent-child relationship between the interface and the implementation class, but a functional relationship. For example, a has B's function.

7. CAN interfaces inherit interfaces? Can an abstract class implement the (implements) interface? Can an abstract class inherit a concrete class )?

A: The interface can inherit the interface. Abstract classes can be implemented (implements) interfaces, and whether abstract classes can inherit object classes, provided that object classes must have clear constructors.

8. How many types of streams are available in Java? JDK provides some abstract classes for each type of stream for inheritance. which classes are they?

A: byte streams and byte streams. Byte streams are inherited from inputstream/outputstream, and bytes streams are inherited from inputstreamreader/outputstreamwriter. There are many other streams in the Java. Io package, mainly to improve performance and ease of use.

9. Conversion Between Basic Data Types

A: byte-> short-> int-> long-> float-> double

Char-> int

For details, see <Java core technology volume 1 V6>

10. Is string the most basic data type?

A: The 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.

11. What is the difference between int and integer?

A: 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.

12. Differences between string and stringbuffer

A: 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.

13. jsp built-in objects and JSP tags

Answer: Nine built-in objects

Request, response, pagecontext, session, application, out, config, page, exception

14. built-in JSP objects and methods.

A: request indicates the httpservletrequest object. It contains information about browser requests and provides several useful methods for obtaining cookie, header, and session data.

Response indicates the httpservletresponse object, and provides several methods (such as cookies and header information) for setting the response to the browser)

The out object is an instance of javax. jsp. jspwriter. It provides several methods for sending output results to the browser.

Pagecontext indicates a javax. servlet. jsp. pagecontext object. It is used to facilitate access to various namespaces and servlet-Related Object APIs, and encapsulates common servlet-related functions.

Session indicates the javax. servlet. http. httpsession object of a request. Session can store user status information

Applicaton indicates a javax. servle. servletcontext object. This helps you find information about the servlet engine and Servlet environment.

Config indicates a javax. servlet. servletconfig object. This object is used to access the initialization parameters of the servlet instance.

Page indicates a servlet instance generated from the page.

15. Differences between the two methods of page redirection in JSP

A: response. sendredirect () and <JSP: Forward>. The former does not forward the request, and the latter forwards the request.

16. Understanding of MVC

A: MVC is a design pattern, namely model, view, and controler.

In the application of the Java B/S structure, We Use Javabean representation of the data model, JSP to process the user view, and control the call and request forwarding of different JSP pages.

17. Introduce the MVC mode. Under what circumstances should I adopt the MVC mode? What are the advantages of the MVC model?

A: MVC is a design pattern, namely model, view, and controler.

In the application of the Java B/S structure, We Use Javabean representation of the data model, JSP to process the user view, and control the call and request forwarding of different JSP pages.

MVC can be used in large and medium-sized projects.

Advantages:

The model and view are separated to enable web designers and programmers to work independently.

The component can increase the reusability of the program and the elasticity of website function expansion.

18. What technologies are used to implement various components of MVC? How to implement it?

A: MVC is short for Model-View-controller. "Model" indicates the business logic of the application (implemented by the JavaBean and EJB components), and "View" indicates the application surface (generated by the JSP page ), "controller" provides application processing process control (generally a servlet). This design model divides the application logic, processing process and display logic into different components for implementation. These components can be used for interaction and reuse.

19. Use of static methods and static variables

Static methods can be accessed directly through the class name, and static variables are shared between different instances of the same class.

20. 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.

21. Differences between collection and collections.

Collection is the upper-level interface of the Collection class. Its Inheritance and its interfaces mainly 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.

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. What is the difference between static variables and instance variables?

Static I = 10; // constant

Class A; A. I = 10; // variable

24. execution time of the finally Clause

Will be executed, unless system. Exit (0) appears before)

25. Let's talk about the 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.

26. 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.

27. How to handle exceptions in Java? What are the meanings of keywords: throws, throw, try, catch, and finally? Can I throw an exception in the try block?

Java uses object-oriented methods to handle exceptions, classify various exceptions, and provides good interfaces. In Java, each exception is an object, which is an instance of the throwable class or other subclass. When a method encounters an exception, an exception object is thrown. The object contains the exception information. The method that calls this object can capture 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 throws an exception. In this case, you can catch it by its type, or finally (finally) is handled by the default processor.

Use try to specify a program to prevent all "exceptions. The catch clause should be followed by the try program to specify the type of the "exception" you want to capture.

Throw statements are used to explicitly throw an "exception ".

Throws is used to indicate various "exceptions" that a member function may throw ".

Finally ensures that a piece of code is executed no matter what "exception" occurs.

You can write a try statement outside a member function call, and write another try statement inside the member function to protect other code. Every time a try statement is encountered, the framework of "exception" is placed on the stack until all try statements are completed. If the try statement at the next level does not process an "exception", the stack will be opened until a try statement that handles this "exception" is encountered.

28. How to ensure data integrity when database operations are suddenly interrupted

Transaction guarantee

29. Scope of public, protected, and private

Other

Inside the protect subclass package

Default package

Private

30. 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.

31. How to Implement servlet single-thread mode

<% @ Page isthreadsafe = "false" %>

32. servlet Lifecycle

The Web container loads the servlet and starts its lifecycle. Call the servlet Init () method to initialize the servlet. Call the Service () method to implement and call different do *** () methods based on different requests. End the service. The Web Container calls the Servlet's destroy () method.

33. Differences between cookies and sessions

Cookies are written on the client. The session data is written on the server and shared between different pages of the same customer.

34. Methods for connecting to the database in JSP

1) connect directly with the application through JDBC

2) connect through the connection pool

35. multi-thread pause and startup

The thread pause method has been discarded, but a Boolean value can be used to empty the thread, so as to pause.

This Boolean value is changed if you want to resume running.

36. What are several implementation methods for multithreading? What are the implementation methods of synchronization?

Multithreading can be implemented in two ways: Inheriting the Thread class and implementing the runnable interface.

There are two types of synchronization implementation: synchronized, wait, and Y.

37. Basic concepts of threads, basic states of threads, and relationships between States

A thread refers to an execution unit that can execute program code during program execution. Each program has at least one thread, that is, the program itself.

Java threads have four states: running, ready, suspended, and ended.

38. Definition of JavaBean

Javabean is a reusable and cross-platform software component. There are two types: Graphical JavaBean and non-graphic JavaBean.

Generally, JavaBean is a public class and must have a non-parameter constructor with the getxxx and setxxx methods.

39. program flow control statements

If... else

For

Switch case

While

Do... while

 

40. & Differences.

& Is a bitwise operator that represents bitwise and operation, & is a logical operator that represents logic and (and ).

41. 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.

42. 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.

 

43. Can anonymous inner class (anonymous internal class) be extends (inherited) other classes, or implements (implemented) interface (Interface )?

It can inherit other classes or complete other interfaces. This method is often used in swing programming.

44. Can an internal class reference its members in the class? Are there any restrictions?

An internal class object can access the content of its external Class Object

45. Can a ". Java" source file contain multiple classes (not internal classes )? What are the restrictions?

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

46. Does Java have a goto?

Reserved Words in Java, which are not currently used in Java.

47. 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.

48. Give me the most common runtime exception.

Except, arraystoreexception, except, failed, cannotredoexception, cannotundoexception, classcastexception, cmcmexception, except, domexception, emptystackexception, except, failed, imagingopexception, failed, missingresourceexception, failed, failed, nullpointerexception, profiledataexception, providerexception, rasterformatexception, securityexception, systemexception, undeclaredthrowableexception, unmodifiablesetexception, unsupportedoperationexception

49. 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.

50. Does list, set, and map inherit from the collection interface?

List, set yes; map is not

 

51. can abstract methods be both static, native, and synchronized?

None

52. 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.

53. Can I inherit the string class?

The string class is a final class, so it cannot be inherited.

54. 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.

55. What are the similarities and differences between synchronized and Java. util. Concurrent. locks. Lock?

The main point is that lock can complete all functions implemented by synchronized.

Major difference: Lock has more precise thread semantics and better performance than synchronized. Synchronized Automatically releases the lock, which must be manually released by the programmer and must be released in the finally clause.

56. can abstract methods be both static, native, and synchronized?

None

57. 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.

58. after an object is passed as a parameter to a method, this method can change the properties of this object and return the changed result. Is it a value transfer or a reference transfer?

Is the value transfer. The Java programming language only transmits parameters by values. 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.

59. 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 an element 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 faster.

60. What are the collection classes you know? What are the main methods?

The most common collection classes are list and map. The specific implementation of list includes arraylist and vector, which are variable-size lists and are suitable for building, storing, and operating the list of elements of any type of object. List is applicable to accessing elements by Numerical index.

Map provides a more general method for storing elements. The Map Collection class is used to store element pairs (called "keys" and "values"). Each key maps to a value.

61. 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.

62. 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 Session Bean, the 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 a large amount of memory on the J2EE server, however, the advantage of stateful Session Bean is that it can maintain the user's status.

63. 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.

64. EJB includes (sessionbean, entitybean) to indicate their lifecycles, 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.

65. EJB roles and three objects

A complete EJB-based Distributed Computing structure consists of six roles, which can be provided by different developers. Each role must follow the EJB specifications provided by Sun, to verify the compatibility between them. These six roles are EJB component developer (enterprise Bean provider), application aggreger (Application aggreger), deployer (deployer), and EJB Server Provider (EJB Server Provider), EJB container provider, System Administrator)

The three objects are remote (local) interface, Home (localhome) interface, and Bean class.

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.