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();
System.out.println(time);

The output looks like this:

1637391898366

Snake Game using Java Swing and Java AWT

Creating a stopwatch in Java

Scanner sc=new Scanner(System.in);
long start,end;
double tim;
System.out.println("Type any character to start the stopwatch");
char s=sc.next().charAt(0);
start=System.currentTimeMillis();
System.out.println("Type any character to stop the stopwatch");
char m=sc.next().charAt(0);
end=System.currentTimeMillis();
tim=(end-start)/1000.0;
System.out.println(tim);

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
y
Type any character to stop the stopwatch
g
5.345

Also read: Get the elapsed time in seconds in Java

Leave a Reply

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