The most common interview questions on Java face

Source: Internet
Author: User
Tags define local event listener finally block object serialization serialization

Exception Handling

1.Java Language How to do exception handling, keywords: throws, throw, try, catch, finally how to use each?

Java uses an object-oriented approach to exception handling, classifies various exceptions, and provides a good interface. In Java, each exception is an object, which is an instance of the Throwable class or its subclasses. When an exception is thrown, a method throws an exception object that contains the exception information, and the method that invokes the object can catch the exception and manipulate it.
Java exception handling is achieved through 5 keywords: try, catch, throw, throws, and finally.
In general, a program is executed with a try, and if the system throws a (throw) an exception object, it can be caught (catch) by its type, or handled by always executing a code block (finally); try to specify a program that prevents all exceptions The catch clause immediately follows the TRY block to specify the type of exception you want to catch, and the throw statement is used to explicitly throw an exception; throws is used to declare a variety of exceptions that a method might throw (while declaring exceptions, allowing moan) Finally, to ensure that a piece of code is executed regardless of the exception, the try statement can be nested, and whenever a try statement is encountered, the structure of the exception is placed in the exception stack until all the try statements are completed. If the next-level try statement does not handle an exception, the exception stack performs a stack operation until it encounters a try statement that handles the exception or eventually throws the exception to the JVM.

2. List some of your common run-time exceptions?
-ArithmeticException (Arithmetic exception)
-ClassCastException (class conversion exception)
-IllegalArgumentException (illegal parameter exception)
-Indexoutofboundsexception (Subscript out-of-bounds exception)
-NullPointerException (null pointer exception)
-SecurityException (Security exception)

What are the two types of exceptions in 3.Java? What difference do they have?

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

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

Both exception and error are subclasses of Throwable.
Error indicates system-level errors and exceptions that the program does not have to handle, a serious problem in situations where recovery is not impossible but difficult, such as memory overflow, which cannot be expected to be handled by the program, and an error that defines an exception that is not expected to be caught by the user program.
Exception represents an exception that needs to be captured or handled by a program, which is a design or implementation problem, that is, if the program is running normally, it never happens. Exception is used for exceptions that can be captured by the user program.

5. What is the importance of the finally code block when dealing with exceptions?

The finally block of code is always executed, regardless of whether an exception is thrown. Even if there is no catch statement and throws an exception, the finally code block will still be executed. Finally, the final code block is primarily used to release resources, such as: I/O buffers, database connections.

6. What happens to the exception object after the exception handling is complete?

The exception object is reclaimed during the next garbage collection.

What is the difference between a 7.finally code block and a Finalize () method?

The finally code block executes regardless of whether or not an exception is thrown, and it is primarily used to release resources that the application occupies. The Finalize () method is a protected method of the object class that is called by the Java Virtual machine before the objects are garbage collected.

Small Java Applications

1. What is an applet?

Java applets are programs that can be included in an HTML page and can be executed by a Java-enabled client browser. Applets are primarily used to create dynamically interacting Web applications.

2. Describe the life cycle of an applet?

Applets can go through the following states:

Init: It will be initialized every time it is loaded.
Start: Executes the applet.
Stop: Ends the execution of the applet.
Destroy: Before uninstalling the applet, do the final cleanup work.

3. What happens when an applet is loaded?

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

What is the difference between 4.Applet and normal Java applications?

Applets are run in Java-enabled browsers, and Java applications are standalone Java programs that can run outside the browser. However, they all need to have a Java virtual machine.

Further, the Java application requires a main function with a specific method signature to begin execution. Java applets do not need such a function to begin execution.

Finally, Java applets typically use very restrictive security policies, and Java applications generally use a more relaxed security policy.

What are the limitations of the 5.Java applet?

Mainly due to security reasons, the following restrictions are imposed on the applet:

Applets cannot be loaded into class libraries or define local methods.
Applets cannot read and write files on a host.
Applets cannot read specific system properties.
An applet cannot initiate a network connection unless it is an on-boarding host.
Applets are not able to open any other programs on the host.

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

When the applet is loaded from the network, the applet is loaded by the applet ClassLoader, 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 the client to read files, write files, load class libraries, and also allow other programs to execute, but not byte-code verification.

What is a 7.applet class loader? What does it do?

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

When a browser loads an applet over a network, the applet's class is placed in a private namespace associated with the source of the applet. Then, the classes that are loaded into the ClassLoader are validated by the validator. The validator checks to see if the class file format adheres to the Java language Specification, ensures that no stack overflow (stacks overflow) or underflow (underflow) is present, and that the parameters passed to the bytecode directive are correct.

What is the 8.applet security Manager? What does it do?

The Applet security Manager is a mechanism that imposes restrictions on applets. Browsers can have only one security manager. The security Manager is created at boot time and cannot be overwritten or extended after it is replaced.

9. What is an untrusted applet?

Untrusted applets are Java applets that cannot access or execute Local system files, and all downloaded applets are untrusted by default.

Swing

1. Say three types of components that support redrawing (painting).

Canvas, Frame, Panel, and applet support redrawing.

2. What is clipping (clipping)?

Limits the drawing operations on a given area or shape to be clipped.

What is the difference between 3.MenuItem and Checkboxmenuitem?

The Checkboxmenuitem class inherits from the MenuItem class, and the Support menu options can be checked or unchecked.

4. How are the elements in the Edge layout (borderlayout) laid out?

The elements inside the borderlayout are laid out according to the east of the container.

5. How are the elements in the grid package layout (gridbaglayout) laid out?

The elements inside the gridbaglayout are laid out according to the grid. Elements of different sizes may occupy more than 1 rows or columns in the grid. Therefore, the number of rows and columns can be different sizes.

What is the difference between 6.Window and frame?

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

7. What is the connection between cropping (clipping) and redrawing (repainting)?

When the window is redrawn by the AWT redraw thread, it sets the clipping region to the area of the window that needs to be redrawn.

8. What is the relationship between the event listener interface (Event-listener interface) and the event adapter (event-adapter)?

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

How does a 9.GUI component handle its own events?

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

What are the advantages of the 10.Java Layout Manager over traditional window systems?

Java uses the layout manager to place components on all Windows platforms in a consistent manner. Because the layout manager does not bind to the absolute size and location of the component, they are able to adapt to the specific platform of a cross-window system.

What design pattern does the 11.Java swing component use?
The swing component in Java uses the MVC (view-model-Controller) design pattern.

12. What is the difference between the pop-up selection menu (Choice) and the list?

The choice is presented in a compact form that requires a drop-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, supporting the selection of one or more elements.

13. What is a layout manager?

The layout manager is used to organize components in containers.

14. What is the difference between the scroll bar (Scrollbar) and the scroll panel (jscrollpane)?

ScrollBar is a component, not a container. And ScrollPane is a container. ScrollPane handles scrolling events on its own.

15. Which swing methods are thread-safe?

There are only 3 thread-safe methods: Repaint (), revalidate (), and invalidate ().

JDBC

1. 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 needing to be concerned with the specifics of a particular database at the bottom.

2. Explain the role of the drive (Driver) in JDBC.

The JDBC driver provides a specific vendor implementation of the JDBC API interface class, and the driver must provide implementations of these classes under the java.sql package: Connection, Statement, Preparedstatement,callablestatement, ResultSet and driver.

What is the function of the 3.class.forname () method?

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

What advantages does 4.PreparedStatement have over statement?

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

5. When do I use CallableStatement? What is the method used to prepare the callablestatement?

CallableStatement is used to execute stored procedures. Stored procedures are stored and provided by the database. Stored procedures can accept input parameters, or they can have return results. The use of stored procedures is highly encouraged because it provides security and modularity. The way to prepare a callablestatement is: Callablestament.preparecall ();

6. What does the database connection pool mean?

Like open Close database connection this interaction with the database can be time consuming, especially when the number of clients increases, which consumes a lot of resources and costs very high. A number of 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 has been used, the connection is returned to the pool for additional requests in the future.

Remote Method Invocation (RMI)

What is the role of Remote Interface (Interface) in 1.RMI?

The remote interface is used to identify which methods are interfaces that can be called by non-local virtual machines. The remote object must implement the remote interface directly or indirectly. A class that implements a remote interface should declare a remote interface that is implemented, define constructors for each remote object, and provide implementations for all methods of the remote interface.

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

The Java.rmi.Naming class is used to store and retrieve references to remote objects inside the remote object registry. Each method of the naming class receives a URL-formatted string object as its argument.

What does 3.RMI bind (binding) mean?

Bindings are procedures for querying a remote object for a remote object, or for registering a name that will be used later. A remote object can be associated with a name using the bind () or rebind () method of the naming class.

What is the difference between the bind () and rebind () methods of the 4.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 the name is already bound, the previous binding will be replaced.

5. What are the steps to make the RMI program work correctly?

In order for the RMI program to run correctly, there are several steps to be included:

Compiles all the source files.
Use rmic to generate stubs.
Start Rmiregistry.
Start the RMI server.
Run the client program.
What role does the 6.RMI stub play?

The stub of the remote object plays the role of the delegate 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 stub method is called, it goes through the following steps:

Initializes the connection to the JVM that contains the remote object.
Serializes the parameters to the remote JVM.
Waits for the result of the method call and execution.
Deserializes the returned value or the exception in which the method did not perform successfully.
Returns the value to the caller.

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

DGC is called distributed garbage collection. RMI uses DGC to do 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 to remote objects.

What is the purpose of using RMI Security Manager (Rmisecuritymanager) in 8.RMI?

Rmisecuritymanager uses the downloaded code to provide a security manager that can be used by RMI applications. If the security manager is not set, the RMI ClassLoader does not download any classes from the remote.

9. Explain the following marshalling and demarshalling.

When an application wants to pass a memory object across the network to another host or persist it to storage, it must convert the object's representation in memory into the appropriate format. This process is called marshalling, and vice versa is demarshalling.

10. Explain the following serialization and deserialization.

Java provides a mechanism called object serialization, which represents the object as a series of bytes containing the object's data, the type information of the object, the type of data inside the object, and so on. Serialization can therefore be seen as a way to flatten objects in order to store them on disk or read them from disk and reconstruct objects. Deserialization is the opposite step of converting an object from a flattened state into an active object.

11. What is RMI?

Java Remote method Invocation (Java RMI) is an object-oriented equivalent form provided by the Java API to remote procedure call (RPC), which supports direct transfer 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 executing on an object that is running locally. Take a look at some of the RMI considerations.

What are the basic principles of 12.RMI architecture?

The RMI architecture is based on a very important principle of separation of behavior definitions and behavior implementations. RMI allows code that defines the behavior to be separated from the code that implements the behavior, and runs on different JVMs.

What are the layers of the 13.RMI architecture?

The RMI architecture is divided into the following layers:

Stub and Skeleton layer (stub and Skeleton layer): This layer is transparent to the programmer, and it is primarily responsible for intercepting the method invocation requests made by the client and then redirecting the request to the remote RMI service.

Remote Reference layer: The second level of the RMI architecture is used to resolve client references to server-side remote objects. This layer resolves and manages client references to server-side remote objects. The connection is point-to.

Transport Layer (Transport layer): This layer is responsible for connecting the two JVMs that participate in the service. This layer is built on a TCP/IP connection between machines on the network. It provides basic connectivity services, and some firewall penetration policies.

Servlet

1. What is a servlet?

A servlet is a Java class used to process client requests and produce Dynamic Web page content. Servlets are primarily used to process or store the data submitted by an HTML form, generating dynamic content and managing state information under a stateless HTTP protocol.

2. Describe the architecture of the servlet.

All servlets must be implemented at the core of the interface is Javax.servlet.Servlet. Each servlet must either implement this interface directly or indirectly, or inherit Javax.servlet.GenericServlet or Javax.servlet.http.HTTPServlet. Finally, the servlet uses multithreading to serve multiple requests in parallel.

What is the difference between 3.Applet and servlet?

Applets are client-side Java programs that run on the client host's browser. The servlet is a component that runs on the server side of the Web service. The applet can use the user interface class, and the servlet does not have a user interface, instead, the servlet waits for the client's HTTP request and then responds to the request.

What is the difference between 4.GenericServlet and HttpServlet?

Genericservlet is a generic protocol-agnostic servlet that implements the servlet and ServletConfig interfaces. Servlets that inherit from Genericservlet should overwrite the service () method. Finally, in order to develop a servlet that can be used on a Web page to serve HTTP protocol requests, your servlet must inherit from HttpServlet. Here is an example of a servlet.

5. Explain the life cycle of the servlet.

For each client request, the servlet engine loads the servlet and invokes its init () method to complete the initialization of the servlet. The Servlet object then processes all subsequent requests from the client by invoking the service () method separately for each request, and finally calls the servlet (translator Note: This should be the servlet instead of the server) destroy () method to remove the servlet.

What is the difference between the 6.doGet () method and the Dopost () method?

The Doget:get method appends the name value pair to the requested URL. Because the URL has a limit on the number of characters, it limits the number of parameter values that are requested by the client. and the parameter values in the request are visible, so the sensitive information cannot be passed in this way.

The Dopost:post method overcomes the limitations of the Get method by placing the request parameter values in the request body, so there is no limit to the number of parameters that can be sent. Finally, the sensitive information passed through the POST request is not visible to external clients.

7. 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. A performance-oriented Web application produces a Web page that contains many kinds of markup language and dynamic content as a response to the request. The service-oriented Web application implements the endpoint of the Web service (endpoint). In general, a Web application can be seen as a set of servlets installed under a specific subset of server URL namespaces.

8. What is the server Side include?

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

9. What is a servlet chain (servlet Chaining)?

A servlet chain is a method that sends the output of a servlet to another servlet. The output from the second servlet can be sent to a third servlet, and so on. The last servlet on the chain is responsible for sending the response to the client.

10. How do I 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 gets the IP address of the client host, and Getremotehost () can obtain the hostname. Look at the example here.

What is the structure of the 11.HTTP response?

The HTTP response consists of three parts:

Status code: Describes the status of the response. Can be used to check whether the request was completed successfully. In the case of a request failure, the status code can be used to identify the cause of the failure. If the servlet does not return a status code, a successful status code of HTTPSERVLETRESPONSE.SC_OK is returned by default.

HTTP headers (HTTP header): They contain more information about the response. For example, the header can specify an expiration date that the response expires, or an encoding format that specifies the content of the transport entity that is used to secure the user. How to retrieve HTTP headers in Serlet look here.

Body: It contains the contents of the response. It can contain HTML code, pictures, and so on. A principal is made up of data bytes that are transmitted immediately behind the head in an HTTP message.

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

A cookie is a piece of information that a Web server sends to a browser. The browser stores cookies for each Web server in a local file. Later, when the browser sends a request to a particular Web server, all cookies stored for that server are sent at the same time. The differences between session and Cookie are listed below:

No matter what the client browser does, the session should work correctly. The client can choose to disable cookies, but the session still works because the client cannot disable the session on the server.

The session and the cookie are not the same in terms of the amount of data stored. Session can store arbitrary Java objects, and cookies can only store objects of type string.

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

The browser and servlet communication use the HTTP protocol.

14. 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 through the pipeline for communicating network protocols. The request to mask requests for other protocols as HTTP is the HTTP tunnel.

What is the difference between the 15.sendRedirect () and Forward () methods?

The Sendredirect () method creates a new request, and the forward () method simply forwards the request to a new target. After redirection (redirect), objects that were within the scope of the previous request are invalidated because a new request is generated, and after forwarding (forwarding), objects within the scope range of the previous request can be accessed. Sendredirect () is generally considered to be slower than forward ().

16. What is URL encoding and URL decoding?

URL encoding is responsible for the space inside the URL and other special characters to replace the corresponding hexadecimal representation, the reverse is decoding.

JSP

1. 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 content with dynamically generated content. Here's a look at the JSP example.

How is the 2.JSP request processed?

The browser first requests a page that ends with a. jsp extension, initiates 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. Note that the JSP file is compiled only when the first request page or the JSP file changes, and then the server calls 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 the JSP.

What are the advantages of 3.JSP?

The advantages of using JSPs are listed below:

JSP pages are dynamically compiled into Servlets, so developers can easily update the presentation code.
JSP pages can be precompiled.
JSP pages can be easily combined with static templates, including HTML or XML, and can easily be combined with code that generates dynamic content.
Developers can provide a custom JSP tag library that allows the page designer to access in the class XML format.
Developers can make logical changes at the component level without having to edit pages that use application-level logic alone.

4. What is a JSP directive (Directive)? What are the different types of directives in a JSP?

Directive is the instruction that the JSP engine will handle when the JSP page is compiled into a servlet. Directive is used to set page-level directives, insert data from an external file, and specify a custom tag library. Directive is defined between <%@ and%>. The different types of directive are listed below:

Include directive (include Directive): used to include files and merge file contents into the current page.
Page directive: Used to define specific properties in a JSP page, such as error pages and buffers.
TAGLIB directive: Used to declare a custom tag library used in a page.

5. What is a JSP action (JSP action)?

The JSP action controls the behavior of the servlet engine in the structure of the XML syntax. When the JSP page is requested, the JSP action is executed. They can be dynamically inserted into the file, re-use the JavaBean component, forward the user to other pages, or generate HTML code for the Java plugin. The available actions are listed below:

jsp:include-contains a file when the JSP page is requested.
jsp:usebean-Find out or initialize the JavaBean.
jsp:setproperty-sets the properties of the JavaBean.
Jsp:getproperty-gets the properties of the JavaBean.
Jsp:forward-forward the request to the new page.
jsp:plugin-generates code for a specific browser.

6. What is Scriptlets?

In JSP technology, Scriptlet is a piece of Java code embedded in a JSP page. Scriptlet is everything inside the tag, and the user can add any valid scriplet between the label and the tag.

7. Where is the declaration (decalaration)?

A declaration is similar to a variable declaration in Java and is used to declare a variable that is subsequently used by an expression or scriptlet. The added declaration must be wrapped up with the start and end tags.

8. What is an expression?

A JSP expression is a Web server that converts the value of a script language expression into a string object that is inserted into the data stream returned to the client. The expression is defined between the two tags, <%= and%>.

9. What does the implied object mean? What are the hidden objects?

JSP implied 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 a clear statement. JSP implicit objects are also called predefined variables. The following lists the implied objects in the JSP page:

Application
Page
Request
Response
Session
exception
Out
Config
PageContext

If wrong, welcome message, I will timely correction, will not mislead others, convenient for everyone to learn, thank you!!!

The most common interview questions on Java face

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.