Write a Java Program to get elapsed time in seconds and milliseconds
This is a Java program that calculates the elapsed time between the start and end of a process. Here's an explanation of each part of the code:
- import java.util.Scanner;: This line imports the Scanner class from the java.util package, which is used to read input from the user.
- public class Elapsed_Time: This line defines a public class called Elapsed_Time, which contains the main method.
- public static void main(String[] args): This is the main method, which is the entry point of the program.
- long start;: This line declares a long variable called start to store the start time of the process.
- long end;: This line declares a long variable called end to store the end time of the process.
- double time;: This line declares a double variable called time to store the elapsed time between the start and end of the process.
- start = System.currentTimeMillis();: This line sets the start variable to the current system time in milliseconds using the currentTimeMillis() method of the System class.
- System.out.print("Enter the Name : ");: This line prints a message asking the user to enter their name.
- Scanner input = new Scanner(System.in);: This line creates a new Scanner object called input to read input from the user.
- String name = input.nextLine();: This line reads a line of text input from the user and stores it in a String variable called name.
- System.out.println("Thanks "+ name +" ! ");: This line prints a message thanking the user for entering their name.
- end = System.currentTimeMillis();: This line sets the end variable to the current system time in milliseconds using the currentTimeMillis() method of the System class.
- time = (end - start) / 1000.0;: This line calculates the difference between the end and start times in milliseconds and divides by 1000.0 to convert the time to seconds, and stores it in the time variable.
- System.out.println("Elapsed Time is : " + time);: This line prints the elapsed time in seconds to the console.
Source Code
import java.util.Scanner;
public class Elapsed_Time
{
public static void main(String[] args)
{
long start;
long end;
double time;
start = System.currentTimeMillis();
System.out.print("Enter the Name : ");
Scanner input = new Scanner(System.in);
String name = input.nextLine();
System.out.println("Thanks "+ name +" ! ");
end = System.currentTimeMillis();
time = (end - start) / 1000.0; //time difference
System.out.println("Elapsed Time is : " + time);
}
}
Output
Enter the Name : Joes
Thanks Joes !
Elapsed Time is : 2.835