Classic java written interview questions

Object oriented programming (OOP)

Java is a computer programming language that supports concurrency, class based and object-oriented. The advantages of object-oriented software development are listed below:

Object oriented programming has many important features, such as encapsulation, inheritance, polymorphism and abstraction. We will analyze these features one by one in the following chapters.

encapsulation

Encapsulation provides objects with the ability to hide internal characteristics and behavior. Object provides methods that can be accessed by other objects to change its internal data. In Java, there are three kinds of modifiers: public, private and protected. Each modifier gives different access rights to other objects under the same package or different packages.

Some of the benefits of using encapsulation are listed below:

Refer to this document for more details and examples of encapsulation.

polymorphic

Polymorphism is the ability of programming languages to show the same interface to different underlying data types. Operations on a polymorphic type can be applied to other types of values.

inherit

Inheritance provides objects with the ability to get fields and methods from the base class. Inheritance provides a reusable line of code, or you can add new features to existing classes without modifying the class.

abstract

Abstraction is the step of separating ideas from concrete instances, so create classes based on their functions rather than implementation details. Java supports the creation of abstract classes that expose only interfaces and do not contain method implementations. The main purpose of this abstraction technology is to separate the behavior of classes from the implementation details.

Differences between abstraction and encapsulation

Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of objects. On the other hand, encapsulation focuses on the details of object behavior. Generally, encapsulation is achieved by hiding the internal state information of objects. Therefore, encapsulation can be regarded as a strategy to provide abstraction.

Common Java problems

1. What is a Java virtual machine? Why is java called a "platform independent programming language"?

Java virtual machine is a virtual machine process that can execute Java bytecode. The Java source file is compiled into a bytecode file that can be executed by the Java virtual machine.

Java is designed to allow applications to run on any platform without requiring programmers to rewrite or recompile each platform separately. The Java virtual machine makes this possible because it knows the instruction length and other features of the underlying hardware platform.

2. What is the difference between JDK and JRE?

The Java runtime environment (JRE) is a Java virtual machine that will execute Java programs. It also contains the browser plug-ins needed to execute the applet. Java development kit (JDK) is a complete Java software development package, including JRE, compiler and other tools (such as Javadoc and Java debugger), which allows developers to develop, compile and execute Java applications.

3. What does the keyword "static" mean? Can you override a private or static method in Java?

The "static" keyword indicates that a member variable or member method can be accessed without the instance variable of the class to which it belongs.

Static methods in Java cannot be overridden because method overriding is based on runtime dynamic binding, while static methods are statically bound at compile time. Static methods are not related to any instance of a class, so they are conceptually inapplicable.

4. Can I access non static variables in the static environment?

Static variable belongs to class in Java, and its value is the same in all instances. When the class is loaded by the Java virtual machine, the static variable is initialized. If your code tries to access non static variables without instances, the compiler will report an error because these variables have not been created and associated with any instances.

5. What data types does Java support? What is an automatic disassembly box?

The 8 basic data types supported by the Java language are:

Auto boxing is a transformation made by the java compiler between the basic data type and the corresponding object wrapper type. For example, convert int to integer, double to double, and so on. On the contrary, it is automatic unpacking.

6. What do you mean by method overriding and method overloading in Java?

Method overloading in Java occurs when two or more methods have the same method name but different parameters in the same class. In contrast, method override means that the subclass redefines the methods of the parent class. Method overrides must have the same method name, parameter list, and return type. The Overrider may not restrict access to the methods it overrides.

7. What is a constructor in Java? What is constructor overloading? What is a copy constructor?

When a new object is created, the constructor is called. Every class has a constructor. If the programmer does not provide a constructor for the class, the java compiler will create a default constructor for the class.

Constructor overloading is very similar to method overloading in Java. You can create multiple constructors for a class. Each constructor must have its own unique parameter list.

Java does not support copy constructors like those in C + +. The difference is that if you do not write your own constructor, Java will not create a default copy constructor.

8. Does Java support multi inheritance?

No, Java does not support multiple inheritance. Each class can inherit only one class, but can implement multiple interfaces.

9. What is the difference between an interface and an abstract class?

Java provides and supports the creation of abstract classes and interfaces. Their implementation has something in common, but the difference is:

You can also refer to the differences between abstract classes and interfaces in jdk8

10. What are value passing and reference passing?

The object is passed by value, which means that a copy of the object is passed. Therefore, even if you change the object copy, it will not affect the value of the source object.

The object is passed by reference, which means that what is passed is not the actual object, but the reference of the object. Therefore, external changes to the reference object are reflected on all objects.

Java thread

11. What is the difference between a process and a thread?

A process is an executing application, and a thread is an execution sequence within a process. A process can have multiple threads. Threads are also called lightweight processes.

12. How many different ways to create threads? Which one do you like? Why?

There are three ways to create threads:

Implementing the runnable interface is more popular because it does not need to inherit the thread class. When other objects have been inherited in the application design, this requires multiple inheritance (Java does not support multiple inheritance) and can only implement the interface. At the same time, the thread pool is also very efficient and easy to implement and use.

13. Briefly explain several available states of threads.

Threads can be in the following states during execution:

14. What is the difference between synchronization method and synchronization code block?

In the Java language, each object has a lock. Threads can use the synchronized keyword to obtain locks on objects. The synchronized keyword can be applied at the method level (coarse-grained locks) or at the code block level (fine-grained locks).

15. How to synchronize threads in the monitor? What level of synchronization should the program do?

The monitor and lock are used together in the Java virtual machine. The monitor monitors a synchronized code block to ensure that only one thread executes the synchronized code block at a time. Each monitor is associated with an object reference. A thread is not allowed to execute synchronous code until it acquires a lock.

16. What is a deadlock?

A deadlock occurs when both processes are waiting for each other to complete execution before continuing. The result is that both processes fall into infinite waiting.

17. How to ensure that n threads can access n resources without causing deadlock?

When using multithreading, a very simple way to avoid deadlock is to specify the order of obtaining locks and force threads to obtain locks in the specified order. Therefore, if all threads lock and release locks in the same order, there will be no deadlock.

Java collection class

18. What are the basic interfaces of the Java collection class framework?

The collection class interface specifies a set of objects called elements. Each specific implementation class of the collection class interface can choose to save and sort elements in its own way. Some collection classes allow duplicate keys, while others do not.

Java collection classes provide a set of well-designed interfaces and classes that support the operation of a group of objects. The most basic interfaces in Java collection classes are:

19. Why do collection classes not implement Cloneable and serializable interfaces?

The semantics and meaning of cloning or serialization are related to the specific implementation. Therefore, it is up to the concrete implementation of the collection class to decide how to clone or serialize.

20. What is an iterator?

The iterator interface provides many methods to iterate over collection elements. Each collection class contains an instance of an iterator that can be returned

Iterative method. The iterator can delete the elements of the underlying collection during the iteration.

21. What is the difference between iterator and listiterator?

Their differences are listed below:

22. What is the difference between fail fast and fail safe?

The security failure of iterator is based on copying the underlying collection, so it is not affected by modifications on the source collection. java. All collection classes under the util package fail quickly, while Java util. All classes under the concurrent package fail safely. Iterators that fail quickly throw

Concurrentmodificationexception exception, and iterators that fail security will never throw such an exception.

23. What is the working principle of HashMap in Java?

HashMap in Java stores elements in the form of key value pairs. HashMap requires a hash function that uses the hashcode () and equals () methods to add and retrieve elements to / from the collection. When the put () method is called, HashMap will calculate the hash value of the key, and then store the key value pair on the appropriate index in the collection. If the key already exists, the value will be updated to the new value.

Some important features of HashMap are its capacity, load factor and threshold resizing.

24. What is the importance of hashcode () and equals () methods?

HashMap in Java uses hashcode () and equals () methods to determine the index of key value pairs. These two methods are also used when obtaining values according to keys. If these two methods are not implemented correctly, two different keys may have the same hash value, so they may be considered equal by the set. Moreover, these two methods are also used to find duplicate elements. Therefore, the implementation of these two methods is very important to the accuracy and correctness of HashMap.

25. What is the difference between HashMap and hashtable?

Both HashMap and hashtable implement the map interface, so many features are very similar. However, they have the following differences:

26. What is the difference between an array and an ArrayList? When should I use array instead of ArrayList?

The differences between array and ArrayList are listed below:

27. What is the difference between ArrayList and LinkedList?

ArrayList and LinkedList both implement the list interface. They have the following differences:

You can also refer to ArrayList vs. LinkedList.

28. What are the comparable and comparator interfaces for? List their differences.

Java provides a comparable interface that contains only one CompareTo () method. This method can sort two objects. Specifically, it returns negative numbers, 0 and positive numbers to indicate that the input object is less than, equal to and greater than the existing object.

Java provides a comparator interface with two methods, compare () and equals (). The compare () method is used to sort the two input parameters. It returns a negative number, 0, and a positive number indicates that the first parameter is less than, equal to, and greater than the second parameter. The equals () method requires an object as a parameter that determines whether the input parameter is equal to the comparator. This method returns true only when the input parameter is also a comparator and the sorting result of the input parameter is the same as that of the current comparator.

29. What is a Java priority queue?

PriorityQueue is an unbounded queue based on priority heap. Its elements are sorted according to natural order. When creating, we can provide it with a comparator responsible for sorting elements. PriorityQueue does not allow null values because they have no natural order, or they do not have any associated comparators. Finally, PriorityQueue is not thread safe, and the time complexity of queue entry and queue exit is O (log (n)).

30. Do you know Big-O notation? Can you give examples of different data structures?

The big O symbol describes how good the size or performance of the algorithm is in the worst scenario when the elements in the data structure increase.

The large o symbol can also be used to describe other behaviors, such as memory consumption. Because collection classes are actually data structures, we generally use large o symbols to select the best implementation based on time, memory and performance. Large o symbols can give a good description of the performance of a large amount of data.

31. How to weigh whether to use unordered arrays or ordered arrays?

The biggest advantage of ordered arrays is that the search time complexity is O (log n), while unordered arrays are o (n). The disadvantage of an ordered array is that the time complexity of the insertion operation is O (n), because elements with large values need to move back to make room for new elements. In contrast, the insertion time complexity of unordered arrays is constant o (1).

32. What are the best practices of the Java collection class framework?

Correctly selecting the type of collection to be used according to the needs of the application is very important for performance. For example, if the size of the element is fixed and can be known in advance, we should use array instead of ArrayList.

Some collection classes allow you to specify the initial capacity. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculating the hash value or expanding the capacity.

Generics are always used for type safety, readability, and robustness reasons. At the same time, using generics can also avoid ClassCastException at run time.

Using the immutable class provided by JDK as the key of map can avoid implementing hashcode () and equals () methods for our own classes.

When programming, the interface is better than the implementation.

When the underlying collection is actually empty, return a collection or array with length 0. Do not return null.

33. What are the differences between the enumeration interface and the iterator interface?

The enumeration is twice as fast as the iterator and uses less memory. However, iterator is much safer than enumeration because other threads cannot modify objects in the collection being traversed by the iterator. At the same time, iterator allows the caller to delete the elements in the underlying collection, which is impossible for enumeration.

34. What is the difference between HashSet and TreeSet?

HashSet is implemented by a hash table, so its elements are unordered. The time complexity of the add(), remove(), contains() method is O (1).

On the other hand, TreeSet is implemented by a tree structure, in which the elements are orderly. Therefore, the time complexity of the add(), remove(), contains() method is O (logn).

Garbage collectors

35. What is the purpose of garbage collection in Java? When is garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer used by the application to release and reuse resources.

36.System. GC () and runtime What does GC () do?

These two methods are used to prompt the JVM for garbage collection. However, it is up to the JVM to start garbage collection immediately or delay it.

37. When is the finalize () method called? What is the purpose of the destructor?

Before releasing the memory occupied by the object, the garbage collector calls the finalize () method of the object. It is generally recommended to release the resources held by the object in this method.

38. If the reference of the object is set to null, will the garbage collector release the memory occupied by the object immediately?

No, this object will be recyclable in the next garbage collection cycle.

39. What is the structure of Java heap like? What is perm Gen space in the heap?

The JVM heap is a runtime data area, and all class instances and arrays allocate memory on the heap. It is created when the JVM starts. The heap memory occupied by objects is collected by the automatic memory management system, that is, the garbage collector.

Heap memory consists of living and dead objects. The surviving objects are accessible to the application and will not be garbage collected. Dead objects are objects that are inaccessible to the application and have not been recycled by the garbage collector. Until the garbage collector recycles these objects, they will occupy heap memory space.

40. What is the difference between a serial collector and a throughput collector?

The throughput collector uses a parallel version of the new generation garbage collector for medium - and large-scale data applications. The serial collector is sufficient for most small applications (about 100m memory is required on modern processors).

41. When can objects be garbage collected in Java?

When an object becomes inaccessible to the application currently using the object, the object can be recycled.

42. Will garbage collection occur in the permanent generation of the JVM?

Garbage collection will not occur in the permanent generation. If the permanent generation is full or exceeds the critical value, a full garbage collection (full GC) will be triggered. If you look closely at the output of the garbage collector, you will find that the permanent generation is also recycled. This is why the correct permanent generation size is very important to avoid full GC. Please refer to Java 8: from permanent generation to metadata area

Note: Java 8 has removed the permanent generation and added a new native memory area called metadata area

exception handling

43. What are the two exception types in Java? What's the difference between them?

There are two kinds of exceptions in Java: checked exceptions and unchecked exceptions. Unchecked exceptions do not need to be declared on the method or constructor, even if the execution of the method or constructor may throw such exceptions, and unchecked exceptions can be propagated outside the method or constructor. Instead, the checked exception must be declared on the method or constructor with the throws statement. Here are some tips for Java exception handling.

44. What is the difference between exception and error in Java?

Exception and error are subclasses of throwable. Exception is used for exceptions that the user program can catch. Error defines exceptions that are not expected to be caught by the user program.

45. What's the difference between throw and throws?

The throw keyword is used to explicitly throw exceptions in the program. On the contrary, the throws statement is used to indicate exceptions that cannot be handled by the method. Each method must specify which exceptions cannot be handled, so the caller of the method can ensure that possible exceptions are handled. Multiple exceptions are separated by commas.

45. What is the importance of finally code blocks in exception handling? The serial number of the author's title is wrong

Finally code blocks are always executed whether or not exceptions are thrown. Even if there is no catch statement and an exception is thrown at the same time, the finally code block will still be executed. Finally, the finally code block is mainly used to release resources, such as I / O buffer and database connection.

46. What happens to the exception object after exception handling?

The exception object will be collected in the next garbage collection process.

47. What is the difference between the finally code block and the finalize () method?

The finally code block will be executed no matter whether an exception is thrown or not. It is mainly used to release the resources occupied by the application. The finalize () method is a protected method of the object class. It is called by the Java virtual machine before the object is garbage collected.

Java applet

48. What is an applet?

Java applets are programs that can be included in HTML pages and executed by Java enabled client browsers. Applet is mainly used to create dynamic interactive web applications.

49. Explain the life cycle of the applet

The applet can go through the following states:

50. What happens when the applet is loaded?

First, create an instance of the applet control class, then initialize the applet, and finally start running.

51. What is the difference between an applet and an ordinary Java application?

Applet runs in a browser with Java enabled. Java application is an independent Java program that can run outside the browser. However, they all need a Java virtual machine.

Further, Java applications need a main function with a specific method signature to start execution. Java applets do not need such functions to start execution.

Finally, Java applets generally use very strict security policies, and Java applications generally use relatively loose security policies.

52. What are the limitations of Java applets?

For security reasons, the following restrictions are imposed on applets:

53. What is an untrusted applet?

Untrusted applets are Java applets that cannot access or execute local system files. By default, all downloaded applets are untrusted.

54. What is the difference between an applet loaded from the network and an applet loaded from the local file system?

When the applet is loaded from the network, the applet is loaded by the applet class loader, which is limited by the applet security manager.

When the applet is loaded from the client's local disk, the applet is loaded by the file system loader.

The applet loaded from the file system allows the client to read files, write files, load class libraries, and execute other programs, but it can not pass bytecode verification.

55. What is the applet class loader? What will it do?

When an applet is loaded from the network, it is loaded by the applet class loader. The class loader has its own Java namespace hierarchy. The class loader ensures that classes from the file system have a unique namespace and classes from network resources have a unique namespace.

When the browser loads an applet over the network, the applet class is placed in a private namespace associated with the applet's source. Then, the classes loaded by the class loader are verified by the verifier. The verifier will check whether the class file format complies with the Java language specification to ensure that there is no stack overflow or underflow, and the parameters passed to bytecode instructions are correct.

56. What is the applet Security Manager? What will it do?

Applet security manager is a mechanism to impose restrictions on applets. Browsers can have only one security manager. The security manager is created at startup and cannot be replaced, overwritten or extended later.

Swing

57. What is the difference between a pop-up selection menu and a list

Choice is presented in a compact form. You need to pull down to see all the options. Only one option can be selected at a time in choice. List can have multiple elements visible at the same time. It supports selecting one or more elements.

58. What is a layout manager?

The layout manager is used to organize components in containers.

59. What is the difference between scrollbar and JScrollPane?

Scrollbar is a component, not a container. Scrollpane is a container. Scrollpane handles scrolling events by itself.

60. Which swing methods are thread safe?

There are only three thread safe methods: repeat(), revalidate(), and invalidate().

61. Name three components that support repainting.

Canvas, frame, panel, and applet support redrawing.

62. What is clipping?

Clipping is done when the drawing operation is limited to a given area or shape.

63. MenuItem and Check@R_108_2419 @What is the difference between MenuItem?

Check@R_108_2419 @MenuItem class inherits from MenuItem class and supports menu options, which can be selected or unchecked.

64. How are the elements in the border layout laid out?

The elements in borderlayout are arranged according to the East, West, North and south of the container.

65. How are the elements in the gridbaglayout laid out?

The elements in gridbaglayout are arranged according to the grid. Elements of different sizes may occupy more than one row or column of the grid. Therefore, the number of rows and columns can have different sizes.

66. What is the difference between window and frame?

The frame class inherits the window class, which defines a main application window that can have a menu bar.

67. What is the relationship between clipping and repainting?

When the window is redrawn by AWT redrawing thread, it will set the clipping area to the area of the window to be redrawn.

68. What is the relationship between event listener interface and Event Adapter?

The event listener interface defines the methods that the event handler must implement for a specific event. The event adapter provides a default implementation for the event listener interface.

69. How does the GUI component handle its own events?

GUI component can handle its own events as long as it implements the corresponding event listener interface and acts as an event listener.

70. What are the advantages of Java layout manager over traditional window system?

Java uses the layout manager to place components on all window platforms in a consistent manner. Because layout managers are not bound to the absolute size and location of components, they can adapt to different platforms across window systems.

71. What design pattern does Java swing component use?

Swing components in Java use the MVC (view model controller) design pattern.

JDBC

72. What is JDBC?

JDBC is an abstraction layer that allows users to choose between different databases. JDBC allows developers to write database applications in Java without caring about the details of the underlying specific database.

73. Explain the role of driver in JDBC.

The jdbc driver provides the implementation of JDBC API interface classes by specific manufacturers. The driver must provide Java The SQL package implements the following classes: connection, statement, Preparedstatement, callablestatement, resultset and driver.

74.Class. What does the forname () method do?

This method is used to load the driver that establishes a connection with the database.

75. What are the advantages of Preparedstatement over statement?

Preparedstatements are precompiled, so performance is better. At the same time, Preparedstatement can be reused for different query parameter values.

76. When to use callablestatement? What is the method used to prepare callablestatement?

Callablestatement is used to execute stored procedures. Stored procedures are stored and provided by the database. Stored procedures can accept input parameters or return results. The use of stored procedures is highly encouraged because it provides security and modularity. To prepare a callablestatement:

1 CallableStament. prepareCall();

77. What does database connection pool mean?

The interaction with the database such as opening and closing the database connection may be time-consuming, especially when the number of clients increases, it will consume a lot of resources and the cost is very high. Many database connections can be established and maintained in a pool when the application server is started. Connection requests are provided by connections in the pool. After the connection is used, the connection is returned to the pool to meet more requests in the future.

Remote method invocation (RMI)

78. What is RMI?

Java Remote method call (Java RMI) is an object-oriented equivalent form of remote procedure call (RPC) provided by Java API. It supports direct transmission of serialized Java objects and distributed garbage collection. A remote method call can be seen as a step to activate a method on a remote running object. RMI is location transparent to the caller because the caller feels that the method is executed on an object running locally. Take a look at some precautions for RMI.

79. What are the basic principles of RMI architecture?

RMI architecture is based on a very important principle of separating behavior definition from behavior implementation. RMI allows code that defines behavior to be separated from code that implements behavior and run on different JVMs.

80. What are the layers of RMI architecture?

RMI architecture is divided into the following layers:

Stub and skeleton layer: this layer is transparent to programmers. It is mainly responsible for intercepting the method call request sent by the client, and then redirecting the request to the remote RMI service.

Remote reference layer: the second layer of RMI architecture is used to resolve the client's reference to the server's remote object. This layer resolves and manages the client's reference to the server's remote object. Connections are point-to-point.

Transport layer: this layer is responsible for connecting the two JVMs participating in the service. This layer is based on the TCP / IP connection between machines on the network. It provides basic connection services and some firewall penetration strategies.

81. What role does the remote interface play in RMI?

The remote interface is used to identify which methods can be called by non local virtual machines. Remote objects must implement remote interfaces directly or indirectly. Classes that implement remote interfaces should declare the implemented remote interfaces, define constructors for each remote object, and provide implementations for all remote interface methods.

82.java. rmi. What role does the naming class play?

java. rmi. The naming class is used to store and obtain references to remote objects in the remote object registry. Each method of naming class receives a string object in URL format as its parameter.

83. What does RMI binding mean?

Binding is the process of associating remote objects or registering names that will be used later in order to query and find remote objects. Remote objects can be associated with names using the bind () or rebind () methods of the naming class.

84. What is the difference between bind () and rebind () methods of naming class?

The bind () method is responsible for binding the specified name to the remote object, and the rebind () method is responsible for rebinding the specified name to a new remote object. If that name is already bound, the previous binding will be replaced.

85. What are the steps to make the RMI program run correctly?

In order for the RMI program to run correctly, the following steps must be included:

86. What role does RMI's stub play?

The stub of the remote object acts as the representative or proxy of the remote object. The caller invokes the method on the local stub, which is responsible for executing the method on the remote object. When the method of stub is called, it will go through the following steps:

87. What is distributed garbage collection (DGC)? How does it work?

DGC is called distributed garbage collection. RMI uses DGC for automatic garbage collection. Because RMI contains references to remote objects across virtual machines, garbage collection is difficult. DGC uses a reference counting algorithm to provide automatic memory management for remote objects.

88. What is the purpose of using RMI Security Manager in RMI?

RMI security manager uses the downloaded code to provide a security manager that can be used by RMI applications. If the security manager is not set, RMI's class loader will not download any classes remotely.

89. Explain Marshall and demarshalling.

When an application wants to transfer memory objects across the network to another host or persist them to storage, it must convert the representation of objects in memory into an appropriate format. This process is called marshalling, and vice versa.

90. Explain serialization and deserialization.

Java provides a mechanism called object serialization. It represents objects as a series of bytes, which contains object data, object type information, type information of data inside objects, and so on. Therefore, serialization can be seen as a way to flatten objects in order to store them on disk or read them out from disk and rebuild them. Deserialization is the reverse step of transforming an object from a flat state to an active object.

Servlet

91. What is a servlet?

Servlet is a Java class used to process client requests and generate dynamic web page content. Servlet is mainly used to process or store the data submitted by HTML forms, generate dynamic content, and manage state information under stateless HTTP protocol.

92. Let's talk about the architecture of servlet.

The core interface that all servlets must implement is javax servlet. Servlet。 Each servlet must implement this interface directly or indirectly, or inherit javax servlet. Genericservlet or javax servlet. http. HTTPServlet。 Finally, servlets use multithreading to serve multiple requests in parallel.

93. What is the difference between applet and servlet?

Applet is a client Java program running on the browser of the client host. Servlet is a component of the server running on the web server. Applets can use user interface classes, while servlets have no user interface. On the contrary, servlets wait for HTTP requests from clients and then generate responses for requests.

94. What is the difference between genericservlet and httpservlet?

Genericservlet is a general protocol independent servlet, which implements the servlet and ServletConfig interfaces. Servlets inherited from genericservlets should override the service () method. Finally, in order to develop a servlet that can be used on Web pages to serve requests using HTTP protocol, your servlet must inherit from httpservlet. Here are examples of servlets.

95. Explain the life cycle of the servlet.

For each client request, the servlet engine loads the servlet and calls its init () method to complete the initialization of the servlet. Then, the Servlet object handles all subsequent requests from the client by calling the service () method for each request individually. Finally, the destroy () method called Servlet should be called to delete the Servlet (Servlet).

96. What is the difference between the doget () method and the dopost () method?

Doget: the get method appends the name value pair to the requested URL. Because the URL limits the number of characters, it limits the number of parameter values used in client requests. And the parameter values in the request are visible, so sensitive information cannot be passed in this way.

Dopost: the post method overcomes the limitation of the get method by putting the request parameter value in the request body. Therefore, there is no limit to the number of parameters that can be sent. Finally, the sensitive information passed through the post request is invisible to the external client.

97. What is a web application?

A web application is a dynamic extension of the web or application server. There are two types of web applications: performance-oriented and service-oriented. Performance oriented web applications will generate interactive web pages containing many markup languages and dynamic content as a response to requests. The service-oriented web application implements the endpoint of web service. Generally speaking, a web application can be regarded as a collection of servlets installed under a specific subset of the server URL namespace.

98. What is server side include?

Server side inclusion (SSI) is a simple interpreted server side scripting language, which is only used on the web most of the time and embedded with servlet tags. The most common scenario for SSI is to include one or more files in a web page of a web server. When the browser accesses the web page, the web server will replace the servlet tag in the web page with the text generated by the corresponding servlet.

99. What is a servlet chain?

Servlet chain is a method to send the output of one servlet to another. The output of the second servlet can be sent to the third servlet, and so on. The last servlet in the chain is responsible for sending the response to the client.

100. How do you know which client machine is requesting your servlet?

The ServletRequest class can find the IP address or host name of the client machine. The getremoteaddr() method obtains the IP address of the client host, and getremotehost() can obtain the host name. Look at the example here.

101. What is the structure of HTTP response?

The HTTP response consists of three parts:

Status code: describes the status of the response. It can be used to check whether the request has been successfully completed. When the request fails, the status code can be used to find out the cause of the failure. If the servlet does not return a status code, it will return a successful status code httpservletresponse by default SC_ OK。

HTTP headers: they contain more information about the response. For example, the header can specify the expiration date that the response is considered to be expired, or specify the encoding format for the user's secure transmission entity content. How to retrieve the HTTP header in the Serlet is shown here.

Body: it contains the content of the response. It can contain HTML code, pictures, and so on. The body consists of the data bytes transmitted immediately after the header in the HTTP message.

102. What is a cookie? What is the difference between session and cookie?

A cookie is a piece of information sent by the web server to the browser. The browser stores cookies for each web server in a local file. In the future, when the browser sends a request to a specific web server, it will also send all cookies stored for the server. The differences between session and cookie are listed below:

103. What protocol is used for browser and servlet communication?

The browser communicates with the servlet using the HTTP protocol.

104. What is an HTTP tunnel?

HTTP tunnel is a technology that uses HTTP or HTTPS to encapsulate a variety of network protocols for communication. Therefore, the HTTP protocol acts as a wrapper to open the pipeline of the network protocol used for communication. Requests that mask requests from other protocols as HTTP are HTTP tunnels.

105. What is the difference between sendredirect () and forward () methods?

The sendredirect () method creates a new request, while the forward () method simply forwards the request to a new target. After redirection, objects within the scope of the previous request will become invalid because a new request will be generated. After forwarding, objects within the scope of the previous request can still be accessed. Sendredirect() is generally considered slower than forward().

106. What is URL encoding and URL decoding?

URL encoding is responsible for replacing the spaces and other special characters in the URL with the corresponding hexadecimal representation, and vice versa.

JSP

107. What is a JSP page?

JSP page is a text document that contains two types of text: static data and JSP elements. Static data can be represented in any text-based format, such as HTML or XML. JSP is a technology that mixes static content and dynamically generated content. Here's an example of JSP.

108. How are JSP requests processed?

The browser first requests a JSP extension at the end of the page, initiate a JSP request, and then the web server reads the request and uses the JSP compiler to convert the JSP page into a servlet class. It should be noted that only when the page is requested for the first time or the JSP file is changed, the JSP file will be compiled, and then the server will call the servlet class to process the browser's request. Once the request execution is complete, the servlet sends the response to the client. Here's how to get the request parameters in JSP.

109. What are the advantages of JSP?

The advantages of using JSP are listed below:

110. What is JSP directive? What are the different types of instructions in JSP?

Directive is the instruction to be processed by the JSP engine when the JSP page is compiled into a servlet. Directive is used to set page level instructions, insert data from external files, and specify custom label libraries. Directive is defined between <% @ and% >. Different types of directive are listed below:

111. What is a JSP action?

JSP actions control the behavior of servlet engine with the structure of XML syntax. When a JSP page is requested, JSP actions are executed. They can be dynamically inserted into files, reuse JavaBean components, forward users to other pages, or generate HTML code for Java plug-ins. The available actions are listed below:

112. What are scriptlets?

In JSP technology, scriptlet is a piece of Java code embedded in JSP pages. Scriptlets are all things inside tags. Users can add any valid scriptlets between tags.

113. Where is the declaration?

Declaration is very similar to variable declaration in Java. It is used to declare variables to be used later by expressions or scriptlets. The added declaration must be wrapped with start and end tags.

114. What is an expression?

[the list is very long and can be published at the top, middle and bottom]

JSP expression is that the web server converts the value of the script language expression into a string object and inserts it into the data stream returned to the client. The expression is defined between <% = and% >.

115. What does the implied object mean? What are the implied objects?

JSP implicit objects are some Java objects in the page. JSP container makes these Java objects available to developers. Developers can use them directly without explicit statements. JSP implicit objects are also called predefined variables. The implicit objects in the JSP page are listed below:

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
分享
二维码
< <上一篇
下一篇>>