Home >Java >javaTutorial >How to use initial in java
The initial method in Java is used to specify the default value in the Optional type, and returns the value when the Optional is empty. This method accepts a non-null value as argument and returns an Optional instance containing that value. The initial method avoids cumbersome null checks and ensures that a non-null value is returned when the value is null.
In Javainitial
Usage
In Java,initial
method is a utility method for the Optional
type that allows you to specify a default value that will be returned if the Optional
is empty.
Syntax:
<code class="java">public static <T> Optional<T> initial(T value)</code>
Parameters:
value
- To be used as the default value non-null value. Return value:
An Optional
instance containing value
.
Usage: The
initial
method is useful for handling values that may be null. By using initial
, you can avoid using cumbersome null checks while still ensuring that a non-null value is returned when the value is null.
Example:
<code class="java">Optional<String> name = Optional.initial("Alice"); if (name.isPresent()) { String n = name.get(); System.out.println("Name: " + n); } else { System.out.println("Name is not present"); }</code>
In the above example, name
is an Optional
containing the value "Alice". The isPresent()
method is used to check if Optional
is not empty, and if so, retrieve the value via the get()
method.
Note: The
initial
method is only available for Optional
types. Optional
is not empty, the default value will not be used. The above is the detailed content of How to use initial in java. For more information, please follow other related articles on the PHP Chinese website!