Technology Sharing

My first interview experience (Java development intern)

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Interviewer's questions

  • I would like to ask if you have done any projects here?
  • Could you please tell me about the projects you have worked on, what technology stack you used, and what content you were responsible for developing? (Project experience)
  • What are the eight basic data types? (Basics)
  • Can you tell me whether the long type can be directly operated? Should I ask whether it can be directly calculated? (Basic)
  • Do you know the singleton pattern? Can you tell me about it? (Design pattern)
  • What is the difference between lazy mode and hungry mode?
  • What are the characteristics of transactions? (Transactions)
  • Can you tell me what exceptions you have encountered while doing a project? (Exception)
  • What are the three commonly used types of time? (Basic)
  • Can you tell me about the three methods of calendar?
  • Let's talk about the life cycle of a session.
  • Have you ever encountered loss of floating point precision while working on a project? How did you solve it?
  • If we use floating point calculations, which data type would you choose?
  • Can you tell me about the commonly used annotations? Spring? Or other ones?
  • Do you know about threads?
    • What is the difference between a thread and a process?
  • So what is thread safety?
  • Can you tell me the difference between == and equals?
  • Do you usually use Linux? Can you briefly talk about some common commands?

problem solved

- 我想问一下你这边有做过什么项目吗?

I think you can just pick one or two projects that you are more familiar with.

- 你方便讲一下你做过的那些项目吗,用了什么技术栈,包括你负责开发的内容是什么?

Pick a project that you are most familiar with.

- 八大基本数据类型是什么?

byte、short、int、long、float、double、char、boolean

- 你说一下long类型能直接运转吗(I think it is asking whether long type data can be directly operated on)

Data of type long can be directly operated on. When you mix int and long values ​​in an expression, the int value will be automatically promoted to long to ensure that the result of the entire expression is of type long.

- 你了解单例模式吗?你可以讲一下吗

The Singleton Pattern is a commonly used software design pattern. Its purpose is to ensure that a class has only one instance and provide a global access point to obtain this unique instance. This pattern is very useful when you need to control resource access, or when instantiating objects consumes resources or is time-consuming, and only one of these resources or instances is needed globally. Common implementations of the Singleton Pattern are mainly: Lazy Man Pattern and Hungry Man Pattern.

- 懒汉模式跟饿汉模式有什么区别?

  1. Can be obtained fromObject initialization timing, thread safety, and resource utilizationCompare in terms of:

      1. Initialization time
      • Lazy Mode:Lazy mode is a延迟加载The singleton pattern. Its characteristics are第一次使用时创建实例对象, rather than creating it when the class is loaded. This pattern avoids the need for instance objects when they are not needed.资源浪费, and only create them when needed.
      • Hungry Man Mode:The hungry man mode is a在类加载时就创建实例The singleton pattern is a special case in which the instance object is created when the class is loaded, regardless of whether it will be used or not. This approach ensures that the same instance object can be obtained in any case, but it may cause some性能和资源上的浪费, especially in some cases where the instance object is not used.
      1. Thread Safety
      • Lazy Mode: The lazy mode itself is非线程安全的, because there is a possibility that multiple threads call the getInstance() method at the same time and enter the judgment statement at the same time, resulting in the creation of multiple instances. In order to achieve thread safety, you can添加synchronized关键字, but this will bring performance overhead. In addition, you can also use double-checked locking and other methods to reduce synchronization overhead.
      • Hungry Man Mode:Hungry Man Mode is线程安全Because the instance object has been created when the class is loaded, there is no competition problem in a multi-threaded environment.
      1. Resource Utilization and Performance
      • Lazy Mode: The lazy mode can save resources because it avoids wasting resources when the instance object is not needed. However, since it needs to be initialized when it is used for the first time, if the initialization process is complex or time-consuming, it may affect performance.
      • Hungry Man Mode:The hungry mode may not be as flexible as the lazy mode in terms of resource utilization, because it will create instance objects regardless of whether they will be used. However, since the instance objects are created when the class is loaded, it will be faster when called for the first time because no initialization is required.
  2. Applicable scene

    • Lazy Mode: Applicable toScenarios where objects are created only when they are used for the first time and there are no complex thread safety requirements during instance object initialization.For example,File ManagerThis is a typical example, because when the application starts, it may not need to read and write files immediately, but perform related operations when needed.
    • Hungry Man Mode:Suitable for scenarios where resources need to be initialized at program startup and are needed throughout the life cycle of the application. For example, a logger is more suitable for the hungry mode because the logging function usually needs to be prepared at the beginning of the application startup and log messages throughout the application operation.
    • To sum up, the lazy mode and the hungry mode each have their own advantages and disadvantages. In practical applications, they should be comprehensively considered and designed according to specific scenarios.

- 说一下事务的几种特性?

  1. Transactions have four basic characteristics, which are also referred to asACIDFeatures include:
    • Atomicity:Atomicity means that all operations in a transaction are either completed or not executed at all. They are an indivisible unit of work. If any error or failure occurs during the execution of a transaction, the operations that have been executed will be undone (rolled back), and the entire transaction will be like an operation that has never occurred. This feature ensures the integrity and consistency of the transaction.
    • Consistency: Consistency means that a transaction must transform the database from one consistent state to another. Before the transaction starts and after the transaction ends, the integrity constraints of the database (such as primary key constraints, foreign key constraints, etc.) are not violated, and all data maintains logical consistency. If the integrity of the database is violated during the execution of a transaction, the transaction will be terminated and the operations that have been executed will be rolled back.
    • Isolation: Isolation means that when multiple transactions are executed concurrently, each transaction is isolated from each other, and the execution of one transaction cannot be interfered with by other transactions. The database system provides a certain level of isolation so that concurrently executed transactions do not interfere with each other, thereby ensuring the correctness and consistency of the data. Isolation is usually achieved through locks (such as row locks, table locks, etc.) or multi-version concurrency control (MVCC) and other mechanisms.
    • DurabilityPersistence: Persistence is also called permanence. It means that once a transaction is committed, its changes to the database are permanent and will not be lost even if the system fails. The database system ensures the persistence of transactions through logs and recovery mechanisms. Even if a system failure occurs, the system can recover the changes made to the database by the committed transactions through logs.

- 说一下你在做项目的过程中都遇到过哪些异常吗?(Just to name a few)

  1. Code Exceptions
    • NullPointerException: Thrown when trying to access or operate an uninitialized object. Commonly seen when forgetting to check whether the object is null and using it directly.
    • ArrayIndexOutOfBoundsException: An invalid index was used when accessing an array (the index was less than 0 or greater than or equal to the array size).
    • ClassCastException: When forcing a type conversion, the object being converted is not an instance of the target type or its subclass.
    • ArithmeticException // by zero: When performing a division operation, the divisor is zero.
  2. Data Exceptions
    • Data format error: When parsing JSON or XML data, the data format does not meet the expectations.
    • Data integrity exception: If a foreign key constraint in the database fails, data integrity rules are violated when trying to insert or update data.
    • No exception found in data: When querying the database, no corresponding data is found according to the given conditions.
  3. Network Exceptions
    • Connection timeout (ConnectTimeoutException): While trying to establish a network connection, the connection request timed out while waiting for a response.
    • Read timeout (SocketTimeoutException): The operation timed out while reading data from the connection.
    • The network is unreachable (UnknownHostException):can not resolve hostname.
    • Connection Refused Error: The target machine rejected the connection request.
  4. System Resource Exceptions
    • OutOfMemoryError: When the JVM tried to allocate memory, there was not enough memory space available.
    • The file does not exist (FileNotFoundException): The file or directory you attempted to access does not exist.
    • Insufficient permissions (SecurityException / AccessDeniedException): Insufficient permissions to perform an operation, such as reading or writing files, accessing network resources, etc.
  5. Third-Party Service Exceptions
    • Service Unavailable (ServiceUnavailableException): The dependent third-party service is temporarily unavailable.
    • API Limitation (RateLimitException): The request to the third-party API exceeded its limit (such as the request frequency limit).
    • Authentication Failure (AuthenticationException): When accessing a third-party service, the authentication information is invalid or expired.
  6. Logical Exceptions
    • Business logic error: For example, the order amount is calculated incorrectly, the inventory is insufficient but the order is still processed, etc.
    • Inconsistent status:A certain state of the system does not meet expectations, resulting in the inability to perform subsequent operations.

- 说一下时间常用的三个类?

LocalDate, LocalTime, LocalDateTime. (You can name any three)

  • In Java, the commonly used classes for processing time are the classes in the java.util.Date, java.util.Calendar, and the java.time packages introduced in Java 8 (such asLocalDate、LocalTime、LocalDateTimewait)

- 说一下日历的三个方法?

When we talk about calendar-related operations, we usually think of the java.util.Calendar class, because it is an abstract class that provides methods for operating calendar fields (such as year, month, day, hour, etc.).Starting from Java 8, a new date and time API (located under the java.time package) was introduced, providing better date and time processing capabilities.

  • Introduction to common methods of LocalDateTime:
      1. Creating LocalDateTime Objects
      • now(): Creates a LocalDateTime object representing the current date and time.
      • of(): Creates a LocalDateTime object by specifying year, month, day, hour, minute, second (and optional nanoseconds). For example: LocalDateTime.of(2023, Month.JANUARY, 1, 12, 0, 0).
      1. Get the properties of a LocalDateTime object
      • getYear(), getMonth(), getDayOfMonth(), getHour(), getMinute(), getSecond(), etc.: are used to obtain the year, month, day, hour, minute, and second attributes of the LocalDateTime object respectively.
      1. Modify the properties of a LocalDateTime object
      • withYear(), withMonth(), withDayOfMonth(), withHour(), withMinute(), withSecond(), etc.: Set a property of a LocalDateTime object to a specified value and return a new LocalDateTime object, leaving the original object unchanged (because LocalDateTime is immutable).
      1. Addition and subtraction of date and time
      • plusYears(), plusMonths(), plusDays(), plusHours(), plusMinutes(), plusSeconds(), etc.: Add the specified period of time to the LocalDateTime object and return a new LocalDateTime object. minusYears(), minusMonths(), minusDays(), minusHours(), minusMinutes(), minusSeconds(), etc.: Subtract the specified period of time from the LocalDateTime object and return a new LocalDateTime object.
      1. Comparing LocalDateTime objects
      • isBefore(LocalDateTime other): Determines whether the current object is earlier than the specified LocalDateTime object.
      • isAfter(LocalDateTime other): Determines whether the current object is later than the specified LocalDateTime object.
      1. Formatting LocalDateTime objects
      • format(DateTimeFormatter formatter): Formats a LocalDateTime object into a string with the specified date and time format. For example: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDateTime = dateTime.format(formatter);.
      1. Calculate time difference
      • Although LocalDateTime itself does not provide a method to directly calculate the time difference, you can use the Duration class or the ChronoUnit class to calculate the time difference between two LocalDateTime objects.
      • Use the Duration class: Duration duration = Duration.between(start, end);, and then you can get the specific value of the time difference, such as seconds, milliseconds, etc., through the duration object.
      • Using the ChronoUnit class: You can specify the unit for calculating the time difference, such as year, month, day, hour, etc. For example: long days = ChronoUnit.DAYS.between(start, end);.

- 说一下session的生命周期吧。

  1. Session Creation
    • Creation time:Session is when the user first accesses the server and requests JSP, Servlet, etc.动态资源Only access HTML, images, etc.静态资源It does not trigger the creation of a Session. If necessary, you can force the creation of a Session by calling request.getSession(true).
    • storage location: Session is stored on the server side and is usually saved in the server's memory for quick access.
  2. Session Maintenance
    • Update the last access time: As long as the user continues to access the server, the server will update the last access time of the session for each request, regardless of whether it reads or writes the session, and maintain the session. This means that the user's session is in the "active" state.
    • Session uniqueness:Each user will have a separate session, which is uniquely identified by a session ID. The session ID is usually sent to the client via a cookie (named JSESSIONID) so that the server can identify different user sessions.
  3. Destroying a Session
    • Automatic Destruction: When the life cycle of the Session times out (that is, there is no activity for a long time), the server automatically clears it from memory. This time is usually configurable, and the default in Tomcat is 30 minutes.
    • Manual destruction: Developers can manually destroy the Session by calling the invalidate() method of the Session. This is usually used in scenarios such as logout and timeout.
  4. Session life cycle settings
    • Set in Servlet: Set the Session timeout in seconds by calling the session.setMaxInactiveInterval(int interval) method.
    • Set in web.xml: In the web.xml file of the web application,通过