Embed presentation
Download to read offline
![Write a program that uses a timer to print the current time once a second. Hint: The following
code prints the current time: Date now = new Date(); System.out.println(now); The Date class is
in the java.util package.
Solution
Answer -
import java.util.*;
import java.text.*;
public class DemoDate
{
public static void main(String args[])
{
int flag=1;
do
{
try
{
Date now = new Date();
System.out.println(now);
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
flag=0;
Thread.currentThread().interrupt();
}
}while(flag!=0);
}
}](https://image.slidesharecdn.com/writeaprogramthatusesatimertoprintthecurrenttimeonceasec-230129053212-72e59be9/85/Write-a-program-that-uses-a-timer-to-print-the-current-time-once-a-sec-docx-1-320.jpg)

The document provides instructions for writing a Java program that prints the current time every second using a timer. It includes a code snippet that utilizes the Date class from the java.util package and handles interruptions. The program runs in a loop until an interruption occurs, pausing for one second between prints.
![Write a program that uses a timer to print the current time once a second. Hint: The following
code prints the current time: Date now = new Date(); System.out.println(now); The Date class is
in the java.util package.
Solution
Answer -
import java.util.*;
import java.text.*;
public class DemoDate
{
public static void main(String args[])
{
int flag=1;
do
{
try
{
Date now = new Date();
System.out.println(now);
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
flag=0;
Thread.currentThread().interrupt();
}
}while(flag!=0);
}
}](https://image.slidesharecdn.com/writeaprogramthatusesatimertoprintthecurrenttimeonceasec-230129053212-72e59be9/85/Write-a-program-that-uses-a-timer-to-print-the-current-time-once-a-sec-docx-1-320.jpg)
