What is Duration.plus() in Java?

plus() is an instance method of the Duration class that is used to add a Duration object to another Duration object.

The plus() method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, use the following import statement.

import java.time.Duration;

Syntax


public Duration plus(Duration duration)

Parameters

  • duration: The duration object to be added.

Return value

This method returns a new Duration object with the specified duration added.

Code

import java.time.Duration;
public class Main{
public static void main(String[] args) {
Duration duration = Duration.ofHours(100);
Duration durationToBeAdded = Duration.ofDays(4);
Duration durationSum = duration.plus(durationToBeAdded);
System.out.printf("%s + %s = %s", duration, durationToBeAdded, durationSum);
}
}

Explanation

  • In line 1, we import the Duration class.
  • In line 6, we define a Duration object of 100 hours called duration.
  • In line 7, we define a Duration object of 4 days called durationToBeAdded, which is to be added to the object created in line 6.
  • In line 8, we add the duration and durationToBeAdded objects with the help of plus() on the duration object.
  • In line 9, we print the objects.

Free Resources