How to create a Stopwatch in Java

In this tutorial, we will be learning how to create a stopwatch in Java. I will be not importing any new packages. Using the basic Java packages we can create a stopwatch.

What is the currentTimeMillis method in Java?

By using java.lang.System class, we can create a stopwatch. To calculate the time we will be using java.lang.System.currentTimeMillis method to calculate the current time. This method doesn’t take any parameter and return a long variable. The method currentTimeMillis returns the difference of time, between the current time and 12:00 am, January 1, 1970. The unit of time is in milliseconds.

long time=System.currentTimeMillis();

The output looks like this:


Snake Game using Java Swing and Java AWT

Creating a stopwatch in Java

Scanner sc=new Scanner(;
long start,end;
double tim;
System.out.println("Type any character to start the stopwatch");
System.out.println("Type any character to stop the stopwatch");

I have initialized two long variables to calculate the starting and ending times. By subtracting them and dividing them by 1000.0 we can calculate the time in seconds.

The output looks like this:

Type any character to start the stopwatch
Type any character to stop the stopwatch

Also read: Get the elapsed time in seconds in Java

Leave a Reply

Your email address will not be published. Required fields are marked *