The first article discusses object-oriented programming and its features, common questions about Java and its features, Java collection classes, garbage collectors, this chapter mainly discusses exception handling, Java applets, Swing, JDBC, remote method calls (RMI), Servlets, and JSP.
Exception handling
Java applet (Applet)
Swing
JDBC
Remote method call (RMI)
Servlet
JSP
Exception handling
43.What are the two exception types in Java? What is the difference between them?
There are two types of exceptions in Java: checked exception and unchecked exception. An exception that is not inspected does not need to be declared on the method or constructor. Even if the execution of the method or constructor may throw such an exception, and the exception that is not inspected can be propagated outside the method or constructor. On the contrary, the checked exception must be declared on the method or constructor using the throws statement. Here are some tips for handling Java exceptions.
44. What is the difference between Exception and Error in Java?
Exception and Error are both subclasses of Throwable. Exception is used for exceptions that can be caught by the user program. Error defines an exception that is not expected to be caught by the user program.
45. What is 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 the method cannot handle. Each method must specify which exceptions cannot be handled, so the caller of the method can ensure that possible exceptions are handled, and multiple exceptions are separated by commas.
45. When handling exceptions, what is the importance of finally code blocks? (Translator's note: The author's title number is wrong)
Whether an exception is thrown or not, finally the code block will always be executed. Even if there is no catch statement and an exception is thrown, the finally code block will still be executed. Finally, I want to say that finally code blocks are mainly used to free resources, such as: I/O buffers, database connections.
46. What changes will happen to the Exception object after the exception processing is completed?
The Exception object will be recycled during the next garbage collection process.
47. What is the difference between finally code block and finalize() method?
Whether an exception is thrown or not, the finally code block will be executed, which is mainly used to free up 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 (Applet)
48.What is Applet?
A java applet is a program that can be included in an HTML page and can be executed by a client browser with Java enabled. Applet is mainly used to create dynamic interactive web applications.
49. Explain the life cycle of Applet
An applet can experience the following state:
50.What happens when an 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 Applet and ordinary Java applications?
Applet is a Java-enabled browser, and Java applications are independent Java programs that can run outside the browser. However, they all need to have Java virtual machines.
Further, Java applications require a main function with a specific method signature to start execution. Java applets do not need such functions to start executing.
Finally, Java applets generally use very strict security policies, while Java applications generally use relatively loose security policies.
52.What are the restrictions of Java applet?
Mainly 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 on the network and an applet loaded from a local file system?
When an 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.
Applets loaded from the file system allow reading, writing, loading class libraries on the client side, and also allow executing other programs, but they cannot pass the bytecode verification.
55.What is an applet class loader? What kind of work does 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 the applet through the network, the applet class is placed in the private namespace associated with the source of the applet. Then, the classes loaded by the class loader are all verified by the validator. The validator will check whether the class file format complies with Java language specifications to ensure that there is no stack overflow or underflow. The parameters passed to the bytecode instruction are correct.
56.What is applet security manager? What kind of work does it do?
The applet security manager is a mechanism to impose restrictions on applets. The browser can have only one security manager. The security manager is created at startup and cannot be replaced or expanded afterwards.
Swing
57. What is the difference between a pop-up selection menu (Choice) and a list (List)
Choice is presented in a compact form and requires a 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, and it supports selecting one or more elements.
58.What is a layout manager?
Layout Manager is used to organize components in containers.
59. What is the difference between a scrollbar and a scroll panel (JScrollPane)?
Scrollbar is a component, not a container. And ScrollPane is a container. ScrollPane handles scrolling events by itself.
60. Which Swing methods are thread-safe?
There are only 3 thread-safe methods: repaint(), revalidate(), and invalidate().
61. Name three components that support redrawing.
Canvas, Frame, Panel, and Applet support redrawing.
62. What is clipping?
Crop the drawing operation that is limited to a given area or shape.
63. What is the difference between MenuItem and CheckboxMenuItem?
The CheckboxMenuItem class inherits from the MenuItem class, and supports menu options that can be selected or not selected.
64. How are the elements in the edge layout (BorderLayout) laid out?
The elements in BorderLayout are arranged according to the east, west, south, north and middle of the container.
65. How are the elements in the grid package layout (GridBagLayout) laid out?
The elements in GridBagLayout are laid out according to the grid. Elements of different sizes may occupy more than 1 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 redrawed by the AWT redraw thread, it sets the crop area to the area of the window that needs to be redrawn.
68. What is the relationship between the event listener interface and the event adapter?
The event listener interface defines the methods that the event processor must implement for a specific event. The event adapter provides a default implementation for the event listener interface.
69.How does GUI component handle its own events?
A GUI component can handle its own events as long as it implements the corresponding event listener interface and regards itself as an event listener.
70.What are the advantages of Java's layout manager over traditional window systems?
Java uses the layout manager to place components on all window platforms in a consistent way. Because layout managers are not bound to the absolute size and position of components, they are able to adapt to the differences between specific platforms across window systems.
71.What design pattern does Java's Swing component use?
The Swing component in Java uses 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 database.
73. Explain the role of driver (Driver) in JDBC.
The JDBC driver provides the implementation of the JDBC API interface class by a specific manufacturer. The driver must provide the following classes of the java.sql package: Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver.
74. What is the function of the Class.forName() method?
This method is used to load drivers that establish connections to the database.
75.What are the advantages of PreparedStatement over Statement?
PreparedStatements are precompiled, so performance will be 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 a CallableStatement?
CallableStatement is used to execute stored procedures. Stored procedures are stored and provided by the database. The stored procedure can accept input parameters or return results. The use of stored procedures is highly encouraged because it provides security and modularity. The method to prepare a CallableStatement is:
CallableStament.prepareCall();
77.What does database connection pool mean?
Interaction with the database like opening and closing the database connection can be time-consuming, especially when the number of clients increases, it consumes a lot of resources and is very costly. Many database connections can be established and maintained in a pool when the application server is started. The connection request is provided by the connection in the pool. After the connection is used, return the connection to the pool to satisfy more future requests.
Remote method call (RMI)
78.What is RMI?
Java Remote Method Call (Java RMI) is an object-oriented equivalent form provided by the Java API for remote procedure calls (RPC). It supports direct transmission of serialized Java objects and distributed garbage collection. A remote method call can be regarded as a step to activate a method on a remote running object. RMI is positionally 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 separation of behavior definition and behavioral realization. RMI allows the code that defines the behavior to be separated from the code that implements the behavior and runs on different JVMs.
80.What are the layers of RMI architecture?
The RMI architecture is divided into the following layers:
Stub and Skeleton layer: This layer is transparent to programmers. It is mainly responsible for intercepting method call requests issued by the client and then redirecting the request to the remote RMI service.
Remote Reference Layer: The second layer of the RMI architecture is used to resolve client references to server-side remote objects. This layer parses and manages client references to server-side remote objects. The connection is point-to-point.
Transport layer: This layer is responsible for connecting two JVMs participating in the service. This layer is built on the TCP/IP connection between machines on the network. It provides basic connectivity services, as well as some firewall penetration policies.
81. What role does the remote interface (Remote Interface) play in RMI?
Remote interfaces are used to identify which methods are interfaces that can be called by non-local virtual machines. Remote objects must directly or indirectly implement remote interfaces. A class that implements a remote interface should declare the implemented remote interface, define a constructor for each remote object, and provide implementation for all remote interface methods.
82.What role does the java.rmi.Naming class play?
The java.rmi.Naming class is used to store and obtain references to remote objects in the remote object registry. Each method of the Naming class receives a URL-formatted String object as its parameter.
83. What does RMI binding mean?
Binding is a process of associating remote objects or registering names after registration in order to query and find remote objects. Remote objects can be associated with names using the bind() or rebind() method of the Naming class.
84. What is the difference between bind() and rebind() methods of the 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 has been bound, the previous binding will be replaced.
85. What are the steps to enable the RMI program to 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 a remote object plays the role of a representative or proxy of a remote object. The caller calls a method on the local stub, which is responsible for executing the method on the remote object. When the stub method is called, the following steps will be gone through:
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 reference counting algorithms to provide automatic memory management to remote objects.
88.What is the purpose of using RMI Security Manager (RMIScurityManager) in RMI?
RMISecurityManager uses downloaded code to provide a security manager that can be used by RMI applications. Without a security manager, RMI's class loader will not download any classes from remotely.
89. Explain Marshalling and demarshalling.
When an application wants to pass memory objects across the network to another host or persist to storage, it must convert the representation of the object in memory into a suitable format. This process is called Marshalling, otherwise it is demarshalling.
90. Explain Serialization and Deserialization.
Java provides a mechanism called object serialization. It represents an object as a series of bytes, including the object's data, the object's type information, the data inside the object, and so on. Therefore, serialization can be seen as a way to flatten the object to store or read it from disk and rebuild it. Deserialization is the opposite step of converting an object from a flat state to a live object.
Servlet
91.What is a Servlet?
Servlet is a Java class used to process client requests and generate dynamic web content. Servlets are mainly used to process or store data submitted by HTML forms, generate dynamic content, and manage state information under the 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 directly or indirectly implement this interface, or inherit javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet. Finally, Servlets can serve multiple requests in parallel using multiple threads.
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 do not have user interfaces. Instead, Servlets wait for the client's HTTP request and then generate a response to the request.
94. What is the difference between GenericServlet and HttpServlet?
GenericServlet is a general protocol-independent Servlet that implements the Servlet and ServletConfig interfaces. Servlets inherited from GenericServlet should override the service() method. Finally, in order to develop a servlet that can be used on a web page to serve HTTP requests, your servlet must be inherited from HttpServlet. Here are examples of Servlets.
95. Explain the life cycle of a servlet.
For each client request, the Servlet engine loads the servlet, calls its init() method, and completes the initialization of the servlet. Then, the Servlet object handles all subsequent requests from the client by calling the service() method individually for each request. Finally, the destroy() method of the Servlet is called (Translator's note: this should be the Servlet instead of the server) to delete the Servlet.
96. What is the difference between doGet() method and doPost() method?
doGet: The GET method appends the name value pair after the requested URL. Because the URL limits the number of characters, the number of parameter values used on the client request is limited. And the parameter values in the request are visible, so sensitive information cannot be passed in this way.
doPOST: The POST method overcomes the limitations of the GET method by placing the request parameter value in the request body, so there is no limit on the number of parameters that can be sent. Finally, sensitive information passed through POST requests is invisible to external clients.
97.What is a web application?
Web applications are dynamic extensions to the web or application server. There are two types of web applications: presentation-oriented and service-oriented. Performance-oriented web applications produce web pages that contain interactive interactions in many markup languages and dynamic content as responses to requests. Service-oriented web applications implement the endpoint of the 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 mostly used only on the Web and is embedded in it with servlet tags. The most commonly used scenario in SSI includes one or more files into a web page of a web server. When the browser accesses a 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 Servlet Chaining?
A Servlet chain is a method that sends the output of one Servlet to another Servlet. The output of the second servlet can be sent to the third servlet, and so on. The last servlet on the chain is responsible for sending the response to the client.
100. How to know which client machine is requesting your Servlet?
The ServletRequest class can find out the IP address or host name of the client machine. getRemoteAddr() method gets the IP address of the client host, getRemoteHost() can get the host name. Take a look at the example here.
101. What is the structure of the HTTP response?
HTTP response consists of three parts:
Status Code: Describes the status of the response. Can be used to check whether the request has been successfully completed. In the event of a request failure, the status code can be used to find out the cause of the failure. If the Servlet does not return the status code, the successful status code HttpServletResponse.SC_OK will be returned by default.
HTTP Headers: They contain more information about the response. For example: the header can specify the expiration date that the response is considered expiration, or specify the encoding format used to transfer entity content to the user securely. How to retrieve HTTP header in Serlet look here.
Body: It contains the content of the response. It can contain HTML code, pictures, and so on. The body is composed of data bytes that are transmitted immediately after the header in an HTTP message.
102.What is cookies? What is the difference between session and cookies?
A cookie is a piece of information sent to a browser by a web server. The browser will store cookies for each web server in the 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 following lists the difference between session and cookies:
No matter what settings the client browser does, the session should work normally. The client can choose to disable cookies, but the session still works because the client cannot disable the server session.
Session and cookies are also different in terms of the amount of data stored. The session can store any Java object, and the cookie can only store objects of String type.
103. What protocol does the browser and Servlet use to communicate?
The browser and Servlet communication use the HTTP protocol.
104. What is an HTTP tunnel?
HTTP tunneling is a technology that uses HTTP or HTTPS to encapsulate multiple network protocols for communication. Therefore, the HTTP protocol plays the role of a wrapper that opens up pipelines for network protocols for communication. A request that covers requests from other protocols into HTTP is an HTTP tunnel.
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 redirecting, objects within the scope of the previous request will be invalid because a new request will be generated. After forwarding, objects within the scope of the previous request will still be accessible. It is generally believed that sendRedirect() is slower than forward().
106.What is URL encoding and URL decoding?
URL encoding is responsible for replacing spaces and other special characters in the URL with the corresponding hexadecimal representation, otherwise it is decoding.
JSP
107.What is a JSP page?
A 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 and dynamically generated content. Here is a JSP example.
108.How are JSP requests processed?
The browser first needs to request a page ending with the .jsp extension, initiate a JSP request, and then the web server reads the request and converts the JSP page into a Servlet class using the JSP compiler. It should be noted that the JSP file will only be compiled when the first request page or JSP file changes, and the server calls the servlet class to process the browser's request. Once the request execution is completed, the servlet will send the response to the client. Here we see how to get request parameters in JSP.
109.What are the advantages of JSP?
The advantages of using JSP are listed below:
110.What is a JSP directive? What are the different types of directives in JSP?
Directive is the instruction that the JSP engine needs to process when a JSP page is compiled into a servlet. Directive is used to set page-level instructions, insert data from external files, and specify a custom tag library. Directive is defined between <%@ and %>. The following are the different types of Directives:
Include directive: Used to include files and merge file contents to the current page.
Page directive: used to define specific properties in JSP pages, such as error pages and buffers.
Taglib directive: Used to declare the custom tag library used in the page.
111.What is JSP action?
JSP actions control the behavior of the Servlet engine with XML syntax structure. When the JSP page is requested, the JSP action will be executed. They can be dynamically inserted into files, reuse JavaBean components, forwarded users to other pages, or generated HTML code for Java plug-ins. The available actions are listed below:
112.What are Scriptlets?
In JSP technology, scriptlets are a piece of Java code embedded in a JSP page. A scriptlet is everything that is located inside a tag. Between the tag, the user can add any valid scriptlet.
113. Where is the declaration (Decalaration)?
Declaration is very similar to variable declarations in Java, and it is used to declare variables to be used by expressions or scriptlets. The added statement must be wrapped with the start and end tags.
114. What is an expression?
[The list is very long and can be published in the upper, middle and lower levels]
JSP expressions are the web server converting the value of the script language expression into a String object and inserting it into the data stream returned to the client. The expression is defined between the two tags <%= and %>.
115. What does an implicit object mean? What are the hidden objects?
JSP implicit objects are some Java objects in the page, and the JSP container allows these Java objects to be used by developers. Developers can use them directly without explicit declarations. JSP implicit objects are also called predefined variables. The following lists the implicit objects in the JSP page:
The above is a compilation of the information for Java interview questions. Thank you for your support to this site!