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
Durationclass. - In line 6, we define a
Durationobject of100hours calledduration. - In line 7, we define a
Durationobject of4days calleddurationToBeAdded, which is to be added to the object created in line 6. - In line 8, we add the
durationanddurationToBeAddedobjects with the help ofplus()on thedurationobject. - In line 9, we print the objects.