How to add a delay in your program in Java

For this Java tutorial today, i will going to teach you how to create or a delay in your program. So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of addDelay.java. We will not import anything here because we will not access any class out from the packages. 2. In your Main, create a For Loop statement that has a variable i in there which starts at 1, end at 5, and has to be incremented by 1.
  1.  for (int i = 1; i <= 5; i++)
3. Inside of it, display the output out from the For Loop using System.out.println.
  1.   System.out.println("i = " + i);
4. Now, create a try and catch method for trapping errors. Here in your try method, we will add a delay in our program by one second before continue to print the next value of the loop using the Thread.sleep() method. If we want to have a one second delay then put 1000 as the parameter of the Thread.sleep() method because it has a millisecond time. In your Catch method, prefer to catch InterruptedException then use printStackTrace() method. This will help to trace the exception and identify which method causes the bug.
  1. try
  2.             {
  3.                 Thread.sleep(1000);
  4.  
  5.             } catch (InterruptedException ie)
  6.             {
  7.                 ie.printStackTrace();
  8.             }
Full Source Code:
  1. public class addDelay
  2. {    
  3.     public static void main(String[] args)
  4.     {
  5.  
  6.         for (int i = 1; i <= 5; i++)
  7.         {
  8.        
  9.             System.out.println("i = " + i);
  10.            
  11.             try
  12.             {
  13.                 Thread.sleep(1000);
  14.  
  15.             } catch (InterruptedException ie)
  16.             {
  17.                 ie.printStackTrace();
  18.             }
  19.         }
  20.     }
  21. }
Press F5 to run this. Download the source code and try it! :) Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment