Complete Works of Java Interview Questions(5)

Complete Works of Java Interview Questions(5)

Baiyu IT Haha
41. Date and time:
-How to get year, month, day, hour, minute, and second?
-How to get the number of milliseconds from 0:0:0 on January 1, 1970 to the present?
-How to get the last day of a month?
-How to format the date?
Answer:
Question 1: Create an instance of java.util.Calendar, call its get() method and pass in different parameters to get the corresponding value of the parameter. You can use java.time.LocalDateTimel to get it in Java 8. The code is shown below.


public class DateTimeTest {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        System.out.println(cal.get(Calendar.YEAR));
        System.out.println(cal.get(Calendar.MONTH));    // 0 - 11
        System.out.println(cal.get(Calendar.DATE));
        System.out.println(cal.get(Calendar.HOUR_OF_DAY));
        System.out.println(cal.get(Calendar.MINUTE));
        System.out.println(cal.get(Calendar.SECOND));
        // Java 8
        LocalDateTime dt = LocalDateTime.now();
        System.out.println(dt.getYear());
        System.out.println(dt.getMonthValue());     // 1 - 12
        System.out.println(dt.getDayOfMonth());
        System.out.println(dt.getHour());
        System.out.println(dt.getMinute());
        System.out.println(dt.getSecond());
    }
}

Question 2: The number of milliseconds can be obtained by the following methods.


Calendar.getInstance().getTimeInMillis();
System.currentTimeMillis();
Clock.systemDefaultZone().millis(); // Java 8

Question 3: The code is shown below.


Calendar time = Calendar.getInstance();
time.getActualMaximum(Calendar.DAY_OF_MONTH);

Question 4: Use the format(Date) method in a subclass of java.text.DataFormat (such as the SimpleDateFormat class) to format the date. Java 8 can use java.time.format.DateTimeFormatter to format the date and time, the code is shown below.


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
class DateFormatTest {
    public static void main(String[] args) {
        SimpleDateFormat oldFormatter = new SimpleDateFormat("yyyy/MM/dd");
        Date date1 = new Date();
        System.out.println(oldFormatter.format(date1));
        // Java 8
        DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date2 = LocalDate.now();
        System.out.println(date2.format(newFormatter));
    }
}

Supplement: Java's time and date API has always been criticized. In order to solve this problem, Java 8 introduced new time and date APIs, including LocalDate, LocalTime, LocalDateTime, Clock, Instant, etc., these classes The design uses the immutable mode, so it is a thread-safe design. If you do not understand these contents, you can refer to my other article "Summary and Thinking on Concurrent Programming in Java".

42. Print the current moment of yesterday.

answer:


import java.util.Calendar;
class YesterdayCurrent {
    public static void main(String[] args){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        System.out.println(cal.getTime());
    }
}

In Java 8, the same function can be achieved with the following code.


import java.time.LocalDateTime;
class YesterdayCurrent {
    public static void main(String[] args) {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime yesterday = today.minusDays(1);

        System.out.println(yesterday);
    }
}

43. Compare Java and JavaSciprt.

Answer: JavaScript and Java are two different products developed by the two companies. Java is an object-oriented programming language launched by the original Sun Microsystems company, which is particularly suitable for Internet application development; while JavaScript is a product of Netscape, which is developed to extend the functionality of the Netscape browser and can be embedded in Web pages to run An explanatory language based on object and event-driven. The predecessor of JavaScript is LiveScript; the predecessor of Java is Oak language.
The following compare the similarities and differences between the two languages:

  • Object-based and object-oriented: Java is a true object-oriented language, even if it is to develop simple programs, objects must be designed; JavaScript is a scripting language, which can be used to make complex interactions with users that have nothing to do with the network software. It is an object-based and event-driven (Event-Driven) programming language, so it itself provides a very rich internal objects for designers to use.
  • Interpretation and compilation: Java source code must be compiled before execution. JavaScript is an interpreted programming language. Its source code does not need to be compiled and is interpreted and executed by the browser. (Almost all current browsers use JIT (just-in-time compilation) technology to improve the efficiency of JavaScript operation)
  • Strongly typed variables and weakly typed variables: Java uses strongly typed variable checking, that is, all variables must be declared before being compiled; variables in JavaScript are weakly typed, and can even be declared before using variables. JavaScript interpreter checks at runtime Infer its data type.
  • The code format is different.

Supplement: The four points listed above are the so-called standard answers circulating on the Internet. In fact, the most important difference between Java and JavaScript is that one is a static language and the other is a dynamic language. The current development trend of programming languages ​​is functional languages ​​and dynamic languages. Classes in Java are first-class citizens, and functions in JavaScript are first-class citizens. Therefore, JavaScript supports functional programming, and you can use Lambda functions and closures. Of course, Java 8 has also begun to support functional Programming provides support for Lambda expressions and functional interfaces. For this type of question, it is better to answer in your own language during the interview to be more reliable. Don't recite the so-called standard answers on the Internet.

44. When to use assert?

Answer: Assertions are a common debugging method in software development, and many development languages ​​support this mechanism. Generally speaking, assertions are used to ensure the most basic and critical correctness of the program. Assertion checking is usually turned on during development and testing. In order to ensure the execution efficiency of the program, the assertion check is usually closed after the software is released. Assertion is a statement containing a Boolean expression. When executing this statement, it is assumed that the expression is true; if the value of the expression is false, the system will report an AssertionError. The use of assertion is shown in the following code:
assert(a> 0); // throws an AssertionError if a <= 0
Assertion can have two forms:
assert Expression1;
assert Expression1: Expression2;
Expression1 should always produce a boolean value .
Expression2 can be any expression that yields a value; this value is used to generate a string message that displays more debugging information.
To enable assertions at runtime, you can use the -enableassertions or -ea flag when starting the JVM. To choose to disable assertions at runtime, you can use the -da or -disableassertions flag when starting the JVM. To enable or disable assertions in the system class, use the -esa or -dsa flags. You can also enable or disable assertions on a package basis.

Note: Assertions should not change the state of the program in any way. Simply put, if you want to prevent code execution when certain conditions are not met, you can consider using assertions to prevent it.

45. What is the difference between Error and Exception?

Answer: Error means system-level errors and exceptions that the program does not need to handle. It is a serious problem when recovery is not impossible but difficult; for example, memory overflow, it is impossible to expect the program to handle such a situation; Exception means that it needs to be caught Or an exception that needs to be handled by the program is a design or implementation problem; that is, it represents a situation that would never happen if the program runs normally.

Interview question: In the 2005 Motorola interview, I once asked the question "If a process reports a stack overflow run-time error, what's the most possible cause?", four options were given: a. lack of memory; b. write on an invalid memory space; c. recursive function calling; d. array index out of boundary. Java programs may also encounter StackOverflowError when running. This is an unrecoverable error. You can only modify the code again. The answer is c. If you write a recursion that cannot converge quickly, it is likely to cause a stack overflow error, as shown below:


class StackOverflowErrorTest {
    public static void main(String[] args) {
        main(null);
    }
}

Tips: Two points must be kept in mind when writing a program with recursion: 1. Recursive formula; 2. Convergence conditions (when no recursion will continue).

46. ​​There is a return statement in try{}, so will the code in finally{} immediately after this try be executed, when is it executed, before or after return?

Answer: Will be executed, before the method returns to the caller.

Note: It is not good to change the return value in finally, because if there is a finally code block, the return statement in try will not immediately return to the caller, but record the return value and call it after the finally code block is executed. The person returns its value, and then if the return value is modified in finally, the modified value will be returned. Obviously, returning or modifying the return value in finally will cause a lot of trouble to the program. In C#, compilation errors are used directly to prevent programmers from doing such nasty things. In Java, the syntax check level of the compiler can also be improved. To generate warnings or errors, Eclipse can be set as shown in the figure. It is strongly recommended to set this as a compilation error.

Complete Works of Java Interview Questions(5)

47. How does Java language handle exceptions? How to use keywords: throws, throw, try, catch, and finally?

Answer: Java uses object-oriented methods to handle exceptions, 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 occurs in a method, an exception object is thrown, the object contains exception information, and the method calling this object can catch the exception and handle it. Java's exception handling is implemented through five keywords: try, catch, throw, throws and finally. Under normal circumstances, try is used to execute a program. If the system throws an exception object, it can be caught by its type or processed by always executing the code block (finally); try is used To specify a program to prevent all exceptions; the catch clause immediately after the try block is used to specify the type of exception you want to catch; the throw statement is used to explicitly throw an exception; throws is used to declare that a method may throw All kinds of exceptions (of course, groaning is allowed when declaring exceptions); finally to ensure that a piece of code is executed no matter what abnormal conditions occur; try statements can be nested, and whenever a try statement is encountered, the abnormal structure will be put Enter the exception stack until all try statements are completed. If the next-level try statement does not handle an exception, the exception stack will perform a pop operation until it encounters a try statement that handles this exception or finally throws the exception to the JVM.

48. What are the similarities and differences between runtime exceptions and checked exceptions?

Answer: Abnormalities indicate abnormal conditions that may occur during the running of the program. Runtime exceptions indicate abnormalities that may be encountered in the normal operation of the virtual machine. It is a common operating error and usually does not occur as long as the program is designed without problems. The checked exception is related to the context in which the program runs. Even if the program design is correct, it may still be caused by problems in use. The Java compiler requires that the method must declare to throw checked exceptions that may occur, but it does not require that it must declare to throw uncaught runtime exceptions. Exceptions, like inheritance, are often abused in object-oriented programming. The following guidelines are given for the use of exceptions in Effective Java:

  • Do not use exception handling for normal control flow (a well-designed API should not force its callers to use exceptions for normal control flow)
  • Use checked exceptions for recoverable conditions and run-time exceptions for programming errors
  • Avoid unnecessary use of checked exceptions (some state detection methods can be used to avoid exceptions)
  • Prioritize standard exceptions
  • The exceptions thrown by each method must be documented
  • Maintain abnormal atomicity
  • Don't ignore the caught exception in catch

    49. List some of your common runtime exceptions?

    answer:

  • ArithmeticException (arithmetic exception)
  • ClassCastException (class conversion exception)
  • IllegalArgumentException (Illegal parameter exception)
  • IndexOutOfBoundsException (subscript out of bounds exception)
  • NullPointerException (Null Pointer Exception)
  • SecurityException (security exception)

    50. Explain the difference between final, finally, and finalize.

    answer:

  • Final: Modifier (keyword) has three uses: If a class is declared as final, it means that it can no longer derive new subclasses, that is, it cannot be inherited, so it is the opposite of abstract. Declaring variables as final ensures that they will not be changed during use. Variables declared as final must be given initial values ​​at the time of declaration, and can only be read and cannot be modified in future references. The method declared as final can also only be used, and cannot be overridden in subclasses.
  • Finally: usually placed after try...catch... The structure always executes the code block, which means that no matter the program is executed normally or an exception occurs, the code here can be executed as long as the JVM is not closed, and the code for releasing external resources can be written in finally block.
  • finalize: A method defined in the Object class. The finalize() method is allowed in Java to do the necessary cleanup work before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed. By overriding the finalize() method, system resources or other cleanup tasks can be performed.

Guess you like

Origin blog.51cto.com/15061944/2593691