isNegative()
is an instance method of the Duration
class that checks if the duration is negative, excluding zero. A Duration
is a directed distance between two points on the timeline, and that is why it can be positive, zero, or negative. This method checks whether the duration is negative or not.
The isNegative()
method is defined in the Duration
class. The Duration
class is defined in the java.time
package. To import the Duration
class, check the following import statement.
import java.time.Duration;
public boolean isNegative()
This method has no parameters.
This method returns true
if the duration length is less than zero. Otherwise it returns false
.
import java.time.Duration;public class Main{public static void main(String[] args) {// Example 1Duration zeroDuration = Duration.ofMinutes(0);System.out.printf("Is '%s' of zero length - %s", zeroDuration, zeroDuration.isNegative());System.out.println();// Example 2Duration positiveDuration = Duration.ofMinutes(5);System.out.printf("Is '%s' of positive length - %s", positiveDuration, positiveDuration.isNegative());System.out.println();// Example 3Duration negativeDuration = Duration.ofMinutes(-5);System.out.printf("Is '%s' of negative length - %s", negativeDuration, negativeDuration.isNegative());System.out.println();}}
In the first example, we created a zero Duration
object with the help of the ofMinutes method, by passing zero as the parameter. The isNegative()
of the created object returns false
, since the length of the duration is zero when projected on a timeline.
In the second example, we created a positive Duration
object with the help of the ofMinutes method, by passing a positive value as the parameter. The isNegative()
of the created object returns false
, since the length of the duration is positive when projected on a timeline.
In the third example, we create a negative Duration
object with the help of the ofMinutes method, by passing a negative value as the parameter. The isNegative()
of the created object returns true
, since the length of the duration is negative when projected on a timeline.