Read Also: Java OOPs Practice Programs for Beginners
What is a Stopwatch?
According to the Oxford dictionary, a stopwatch is a watch that can be started and stopped by pressing a button, so that you can measure exactly how long something takes.
Stopwatch in Java with source code
import java.util.Scanner;
public class StopWatch {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter any character to start the stopwatch");
char start = scan.next().charAt(0);
long startTime = System.currentTimeMillis();
System.out.println("Enter any character to stop the stopwatch");
char stop = scan.next().charAt(0);
long endTime = System.currentTimeMillis();
double time = (endTime-startTime)/1000.0;
System.out.println(time);
}
}
Output:
We have initialized two long variables to calculate the start and end times. By calculating the difference between them and dividing them by 1000.0, we can measure exactly how long something takes.
That's all for today. Please mention in the comments if you have any questions related to how to create a stopwatch in Java with source code.