SoFunction
Updated on 2025-04-14

Interpretation of Java usage code

Java usage code

is a static method in the Java standard library, located inin class.

This method is used to check whether the given object reference is non-empty (i.e. notnull)。

  • The basic usage is as follows:
public static boolean nonNull(Object obj) {
    return obj != null;
}
  • Example of usage:
import ;

public class Example {
    public void someMethod(String input) {
        if ((input)) {
            // Action performed when the input is not null            ("Input is not null, its value: " + input);
        } else {
            throw new IllegalArgumentException("Input cannot be null");
        }
    }
}

// use:Example example = new Example();
String someString = "Hello";
(someString); // If someString is not null, the message will be printed
// Or used as a predicate in stream operationsList<String> list = ...; // Assume it is a list of strings()
    .filter(Objects::nonNull)
    .forEach(::println); // This will print only the list of non null Elements

Notice:

  • ()The method does not throw an exception, it simply returns a boolean value indicating whether the object is not empty.
  • If you need to throw an exception when the object is null, you should use()method, which will be thrown when the incoming object is nullNullPointerException

() and ()

  • contrast:
Traditional writing Objects Method Applicable scenarios
if (user != null) if ((user)) Forward operation (Logistics are executed only when the object exists)
if (user == null) if ((user)) Reverse operation (provides alternate logic when the object is empty)
  • Examples of using Stream streams:
List<String> names = ()
    .filter(Objects::nonNull) // Filter null user objects    .map(User::getName)
    .collect(());

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.