Stopwatch in Java with source code

In this post, I will be sharing how to create a stopwatch in Java with source code. We will be using basic Java packages to achieve our goal. In simple words, we will be using java.lang.System class's currentTimeMillis() method. currentTimeMillis() method returns the current time in milliseconds.

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:
Stopwatch java program 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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry