Complete Works of Java Interview Questions(10)

Complete Works of Java Interview Questions(10)

Baiyu IT haha

91. Write a singleton class in Java.

answer:

  • Hungry singleton

public class Singleton {
    private Singleton(){}
    private static Singleton instance = new Singleton();
    public static Singleton getInstance(){
            return instance;
    }
}
  • Lazy singleton

public class Singleton {
    private static Singleton instance = null;
    private Singleton() {}
    public static synchronized Singleton getInstance(){
        if (instance == null)
         instance = new Singleton();
      return instance;
    }
}

Note: There are two precautions for implementing a singleton. ① Make the constructor private and not allow the outside world to create objects through the constructor; ② Return the only instance of the class to the outside world through a public static method. There is a question to think about: Spring's IoC container can create singletons for ordinary classes. How does it do it?

92. What is UML?

Answer: UML is the abbreviation of Unified Modeling Language (Unified Modeling Language). It was published in 1997. It integrates the existing object-oriented modeling language, methods and processes at that time. It is a graph that supports modeling and software system development. It provides modeling and visualization support for all stages of software development. Using UML can help communication and communication, assist in application design and document generation, and can also explain the structure and behavior of the system.

93. What are the commonly used diagrams in UML?

Answer: UML defines a variety of graphical symbols to describe part or all of the static structure and dynamic structure of a software system, including: use case diagram, class diagram, sequence diagram, and collaboration Diagram (collaboration diagram), state diagram (statechart diagram), activity diagram (activity diagram), component diagram (component diagram), deployment diagram (deployment diagram), etc. Among these graphical symbols, three diagrams are the most important. They are: use case diagram (used to capture requirements and describe the functions of the system, through which you can quickly understand the functional modules of the system and their relationships), class diagrams (describe classes) As well as the relationship between classes and classes, you can quickly understand the system through this diagram), sequence diagrams (describe the interaction between objects when performing specific tasks and the execution sequence, through this diagram, you can understand the messages that the object can receive, that is, the object Services that can be provided to the outside world).
Use case diagram:
Complete Works of Java Interview Questions(10)
Class diagram:
Complete Works of Java Interview Questions(10)
Sequence diagram:
Complete Works of Java Interview Questions(10)

94. Write a bubble sort in Java.

Answer: Bubble sort is almost written by a programmer, but not everyone can do how to write a high bubble sort during an interview. Here is a reference code:


import java.util.Comparator;/**
 * 排序器接口(策略模式: 将算法封装到具有共同接口的独立的类中使得它们可以相互替换)
  */
public interface Sorter {
   /**
    * 排序
    * @param list 待排序的数组
    */
   public <T extends Comparable<T>> void sort(T[] list);   /**
    * 排序
    * @param list 待排序的数组
    * @param comp 比较两个对象的比较器
    */
   public <T> void sort(T[] list, Comparator<T> comp);
}
import java.util.Comparator;
public class BubbleSorter implements Sorter {
    @Override
    public <T extends Comparable<T>> void sort(T[] list) {
        boolean swapped = true;
        for (int i = 1, len = list.length; i < len && swapped; ++i{
          swapped = false;
          for (int j = 0; j < len - i; ++j) {
            if (list[j].compareTo(list[j + 1]) > 0) {
               T temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;
               swapped = true;
             }
            }
        }
    }
    @Override
    public <T> void sort(T[] list, Comparator<T> comp) {
      boolean swapped = true;
       for (int i = 1, len = list.length; i < len && swapped; ++i){
          swapped = false;
          for (int j = 0; j < len - i; ++j) {
            if (comp.compare(list[j], list[j + 1]) > 0) {
               T temp = list[j];
               list[j] = list[j + 1];
               list[j + 1] = temp;
               swapped = true;
             }
            }
        }
    }
}

95. Write a binary search in Java.

Answer: Binary search, also known as binary search and binary search, is a search algorithm to find a specific element in an ordered array. The search process starts from the middle element of the array. If the middle element happens to be the element to be searched, the search process ends; if a particular element is greater than or less than the middle element, search in the half of the array that is greater or less than the middle element , And start the comparison from the middle element just like the beginning. If the array is already empty at a certain step, it means that the specified element cannot be found. This search algorithm reduces the search range by half each time it compares, and its time complexity is O(logN).


import java.util.Comparator;
public class MyUtil {
   public static <T extends Comparable<T>> int binarySearch(T[] x, T key) {
  return binarySearch(x, 0, x.length- 1, key);
   }
     // 使用循环实现的二分查找
   public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {
     int low = 0;
     int high = x.length - 1;
     while (low <= high) {
       int mid = (low + high) >>> 1;
       int cmp = comp.compare(x[mid], key);
       if (cmp < 0) {
            low= mid + 1;
       }else if (cmp > 0) {
            high= mid - 1;
       }else {
            return mid;
       }
      }
      return -1;
   }
    // 使用递归实现的二分查找
   private static<T extends Comparable<T>> int binarySearch(T[] x, int low, int high, T key) {
     if(low <= high) {
       int mid = low + ((high -low) >> 1);
       if(key.compareTo(x[mid])== 0) {
          return mid;
       }else if(key.compareTo(x[mid])< 0) {
          return binarySearch(x,low, mid - 1, key);
       } else {
          return binarySearch(x,mid + 1, high, key);
       }
      }
      return -1;
   }
}

Explanation: Two versions of binary search are given in the above code, one is realized by recursion and the other is realized by loop. It should be noted that the (high + low) / 2 method should not be used when calculating the intermediate position, because the addition operation may cause the integer to go out of bounds, one of the following three methods should be used here: low + (high-low) / 2 or low + (high-low) >> 1 or (low + high) >>> 1 (>>> is logical right shift, right shift without sign bit)

96. Explain the difference between Servlet and CGI?

Answer: The difference between Servlet and CGI is that Servlet is in the server process. It runs its service() method in multi-threaded mode. One instance can serve multiple requests, and its instance is generally not destroyed. However, CGI does everything for each request. A new process is generated, and the service is destroyed after completion, so the efficiency is lower than Servlet.

Supplement: Sun Microsystems released Servlet technology in 1996 to compete with CGI. Servlet is a special Java program. A Java-based Web application usually contains one or more Servlet classes. Servlet cannot be created and executed by itself. It runs in a Servlet container. The container passes the user's request to the Servlet program and sends the Servlet's response back to the user. Usually a Servlet will be associated with one or more JSP pages. In the past, CGI was often criticized for performance overhead issues. However, Fast CGI has already solved the CGI efficiency problem, so you don’t need to be criticized about CGI during the interview. In fact, many websites you are familiar with use CGI. technology.

97. What methods are there in the Servlet interface?

Answer: The Servlet interface defines 5 methods, of which the first three methods are related to the Servlet life cycle:


- void init(ServletConfig config) throws ServletException 
- void service(ServletRequest req, ServletResponse resp) throws ServletException, java.io.IOException 
- void destory() 
- java.lang.String getServletInfo() 
- ServletConfig getServletConfig()

After the web container loads the servlet and instantiates it, the servlet life cycle begins, and the container runs its init() method to initialize the servlet; when the request arrives, the service() method of the servlet is called, and the service() method will be called as needed to correspond to the request When the server is closed or the project is uninstalled, the server will destroy the Servlet instance, and the destroy() method of the Servlet will be called.

98. What is the difference between forward and redirect?

Answer: Forward is the transfer of control in the container. The server requests resources. The server directly accesses the URL of the target address, reads the response content of that URL, and then sends the content to the browser. The browser does not know the server at all. Where did the sent content come from, so its address bar is still the original address. Redirect means that the server sends a status code based on logic to tell the browser to request that address again. Therefore, you can see the link address after the jump in the address bar of the browser. Obviously, redirect cannot access the resources protected by the server. But you can redirect from one website to another website. Forward is more efficient, so try to use forward when you need it (by calling the forward() method of the RequestDispatcher object, which can be obtained through the getRequestDispatcher() method of the ServletRequest object), and this also helps to hide the actual link; in some cases Next, if you need to access a resource on another server, you must use redirection (implemented by calling its sendRedirect() method by the HttpServletResponse object).

99. What are the built-in objects of JSP? What are the roles?

Answer: JSP has 9 built-in objects:

  • request: Encapsulate the client's request, which contains the parameters from the GET or POST request;
  • response: encapsulate the server's response to the client;
  • pageContext: other objects can be obtained through this object;
  • session: the object that encapsulates the user session;
  • application: the object that encapsulates the operating environment of the server;
  • out: The output stream object that the output server responds to;
  • config: The configuration object of the Web application;
  • page: JSP page itself (equivalent to this in Java program);
  • exception: The object that encapsulates the page that throws the exception.

Supplement: If you use Servlet to generate dynamic content in web pages, it is undoubtedly very tedious work. On the other hand, all text and HTML tags are hard-coded, and even minor changes need to be recompiled. JSP solves these problems of Servlet. It is a good supplement to Servlet. It can be used exclusively as a user to present a view (View), and Servlet as a controller (Controller) is specifically responsible for processing user requests and forwarding or redirecting to a certain page. Many Java-based Web development uses both Servlet and JSP. A JSP page is actually a Servlet, and the server (Servlet container) that can run Servlet is usually also a JSP container, which can provide a running environment for JSP pages. Tomcat is a Servlet/JSP container. When requesting a JSP page for the first time, the Servlet/JSP container first converts the JSP page into an implementation class of a JSP page, which is a Java class that implements the JspPage interface or its sub-interface HttpJspPage. The JspPage interface is a sub-interface of Servlet, so each JSP page is a Servlet. After the conversion is successful, the container will compile the Servlet class, then the container loads and instantiates the Java bytecode, and executes the life cycle operations that it usually does on the Servlet. For subsequent requests to the same JSP page, the container will check whether the JSP page has been modified, and if it has been modified, it will retransform and recompile and execute it. If not, execute the existing Servlet instance in memory. We can see everything by looking at the Java program corresponding to a piece of JSP code, and the mystery of the 9 built-in objects will be unveiled.

JSP page:


<%@ page pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%><!DOCTYPE html><html>
  <head>
    <base href="<%=basePath%>">
    <title>首页</title>
    <style type="text/css">
        * { font-family: "Arial"; }
    </style>
  </head>

  <body>
    <h1>Hello, World!</h1>
    <hr/>
    <h2>Current time is: <%= new java.util.Date().toString() %></h2>
  </body></html>

The corresponding Java code:


/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.52
 * Generated at: 2014-10-13 13:28:38 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */package org.apache.jsp;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
        implements org.apache.jasper.runtime.JspSourceDependent {

    private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory
            .getDefaultFactory();

    private static java.util.Map<java.lang.String, java.lang.Long> _jspx_dependants;

    private javax.el.ExpressionFactory _el_expressionfactory;
    private org.apache.tomcat.InstanceManager _jsp_instancemanager;

    public java.util.Map<java.lang.String, java.lang.Long> getDependants() {
        return _jspx_dependants;
    }

    public void _jspInit() {
        _el_expressionfactory = _jspxFactory.getJspApplicationContext(
                getServletConfig().getServletContext()).getExpressionFactory();
        _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory
                .getInstanceManager(getServletConfig());
    }

    public void _jspDestroy() {
    }

    public void _jspService(
            final javax.servlet.http.HttpServletRequest request,
            final javax.servlet.http.HttpServletResponse response)
            throws java.io.IOException, javax.servlet.ServletException {
        // 内置对象就是在这里定义的
        final javax.servlet.jsp.PageContext pageContext;
        javax.servlet.http.HttpSession session = null;
        final javax.servlet.ServletContext application;
        final javax.servlet.ServletConfig config;
        javax.servlet.jsp.JspWriter out = null;
        final java.lang.Object page = this;
        javax.servlet.jsp.JspWriter _jspx_out = null;
        javax.servlet.jsp.PageContext _jspx_page_context = null;

        try {
            response.setContentType("text/html;charset=UTF-8");
            pageContext = _jspxFactory.getPageContext(this, request, response,
                    null, true, 8192, true);
            _jspx_page_context = pageContext;
            application = pageContext.getServletContext();
            config = pageContext.getServletConfig();
            session = pageContext.getSession();
            out = pageContext.getOut();
            _jspx_out = out;

            out.write('\r');
            out.write('\n');

            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + path + "/";// 以下代码通过输出流将HTML标签输出到浏览器中            out.write("\r\n");
            out.write("\r\n");
            out.write("<!DOCTYPE html>\r\n");
            out.write("<html>\r\n");
            out.write("  <head>\r\n");
            out.write("    <base href=\"");
            out.print(basePath);
            out.write("\">\r\n");
            out.write("    <title>首页</title>\r\n");
            out.write("    <style type=\"text/css\">\r\n");
            out.write("    \t* { font-family: \"Arial\"; }\r\n");
            out.write("    </style>\r\n");
            out.write("  </head>\r\n");
            out.write("  \r\n");
            out.write("  <body>\r\n");
            out.write("    <h1>Hello, World!</h1>\r\n");
            out.write("    <hr/>\r\n");
            out.write("    <h2>Current time is: ");
            out.print(new java.util.Date().toString());
            out.write("</h2>\r\n");
            out.write("  </body>\r\n");
            out.write("</html>\r\n");
        } catch (java.lang.Throwable t) {
            if (!(t instanceof javax.servlet.jsp.SkipPageException)) {                out = _jspx_out;
                if (out != null && out.getBufferSize() != 0)
                    try {                        out.clearBuffer();
                    } catch (java.io.IOException e) {
                    }
                if (_jspx_page_context != null)
                    _jspx_page_context.handlePageException(t);
                else
                    throw new ServletException(t);
            }
        } finally {
            _jspxFactory.releasePageContext(_jspx_page_context);
        }
    }
}

100. The difference between get and post request?

Answer:
①get request is used to obtain resources from the server, and post is used to submit data to the server;
②get adds the data in the form to the URL pointed to by action in the form of name=value, and both use "?" Connection, and the "&" connection between each variable; post is to put the data in the form in the request header or message body of the HTTP protocol and pass it to the URL pointed to by the action;
③The data transmitted by get is subject to the URL length limit (1024 Bytes); while post can transmit a large amount of data, upload files usually use the post method;
④When using get, the parameters will be displayed on the address bar. If the data is not sensitive data, then you can use get; for sensitive data, it is still used by the application post;
⑤get uses the MIME type application/x-www-form-urlencoded URL encoding (also called percent sign encoding) text format to pass parameters to ensure that the transmitted parameters are composed of text that follows the specification, for example, the encoding of a space is "%20".

Guess you like

Origin blog.51cto.com/15061944/2593708