Skip to main content

Advanced Java 进阶特性

Exception 异常

1. what is the checked exception and unchecked exception in Java, could you give one example?

  • Checked Exception: These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the catch/throws keyword.

    • ClassNotFoundException
    • SQLException
  • Unchecked Exception: These are the exceptions that are not checked at compile time. It is up to the programmers to be civilized, and specify or catch the exceptions.

    • NullPointerException
    • NumberFormatException 字符串转换为数字
    • ArrayIndexOutOfBoundsException 数组越界
    • ClassCastException 类型转换错误
    • ArithmeticException 算术错误

Exception Handling methods 常用的异常处理方法

1. Basic try-catch-finally

try {
// 可能会引发异常的代码
int result = 10 / 0;
} catch (ArithmeticException e) {
// 处理异常
System.out.println("Cannot divide by zero");
} finally {
// 无论是否发生异常,都会执行的代码
System.out.println("This block always executes");
}

2. Multiple catch blocks

当你的代码可能引发多种类型的异常时,你可以为每种异常类型使用单独的 catch 块。

try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
} catch (Exception e) {
System.out.println("A general exception occurred");
}

3. Nested try-catch blocks

try {
// Outer try block
try {
// Inner try block
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Inner catch block: Cannot divide by zero");
}
} catch (Exception e) {
System.out.println("Outer catch block: A general exception occurred");
}

4. throws Keyword

当你不想在当前方法中处理异常,而是想将异常传递给调用此方法的代码,你可以使用 throws 关键字。

public void someMethod() throws CustomException {
if (someCondition) {
throw new CustomException("An error occurred");
}
}

5. Custom Exception

自定义异常。通过扩展 Exception 类来完成的

// Custom exception class
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

// Usage
public void someMethod() throws CustomException {
if (someCondition) {
throw new CustomException("This is a custom exception");
}
}

6. try-with-resources Statement

对于实现了 AutoCloseable 或 Closeable 接口的资源(如文件、数据库连接等),你可以使用 try-with-resources 来确保资源在使用后被正确关闭。

try (FileInputStream fis = new FileInputStream("somefile.txt")) {
// Use the resource
} catch (IOException e) {
System.out.println("Error reading the file");
}
// The resource will be closed automatically after the try block.

Java 8 Features

1. What is Java 8 new features?

  • Default method in interface: The concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

  • Static method in interface: Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementation class.

  • Functional interface

    • Has one single Abstract method
    • @FunctionalInterface - for sanity check
    • Can have default methods
    • Lambda is the implementation of the abstract method
  • Lambda

    • To Replace anonymous inner class
    • Work with functional interface
    • Lambda can use unchanged variable outside of lambda
  • Optional: To avoid Null checks and run time NullPointerExceptions

  • Method reference

  • Stream

2. what is optional? why do you use it? write an optional example

Optional can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run.

// Java program with Optional Class

import java.util.Optional;

public class OptionalDemo {
public static void main(String[] args) {
String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);

// check if object contains null value
if (checkNull.isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
}
else
System.out.println("word is null");
}
}

3. Lambda

A lambda expression is a short block of code. Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method.

  • lambda expressions introduce functional style processing in Java.
  • It helps the writing of compact and easy-to-read code.
  • Lambda expressions are a natural replacement for anonymous classes such as method arguments.
  • One of their main uses is to define inline implementations of functional interfaces.

4. [Stream] What Is the Difference Between Intermediate and Terminal Operations?

A stream is an iterator whose role is to accept a set of actions to apply on each of the elements it contains.

  • Intermediate operations are those operations that return Stream itself, allowing for further operations on a stream.
    • filter, map and flatMap.
  • terminal operations terminate the pipeline and initiate stream processing.
    • forEach, reduce, Collect and sum.

5. Have you done any work with atomics?

  • java.util.concurrent.atomic is a small toolkit of classes to perform atomic operations. They support lock-free, thread-safe programming on single variables. 性能更好的线程安全类。
  • Instances of Atomic classes (AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference) maintain values that are accessed and updated using methods otherwise available for fields using associated atomic VarHandle operations.
  • Internally, the atomic classes make heavy use of compare-and-swap (CAS), an atomic instruction directly supported by most modern CPUs. Those instructions usually are much faster than synchronizing via locks. 其内部使用 CAS 操作,速度比锁操作更快。

Stream 流式编程

1. Find the second smallest and second largest number in an array

public class SecondSmallestLargestFinder {

public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(12, 7, 3, 9, 15, 6, 10);

Optional<Integer> secondSmallest = numbers.stream()
.distinct()
.sorted()
.skip(1)
.findFirst();

Optional<Integer> secondLargest = numbers.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst();

System.out.println("Numbers: " + numbers);
System.out.println("Second Smallest: " +
(secondSmallest.isPresent() ? secondSmallest.get() : "No such element"));
System.out.println("Second Largest: " +
(secondLargest.isPresent() ? secondLargest.get() : "No such element"));
}
}