rand() and srand() Functions in Java

This is a java program to generate random numbers using rand() and srand() functions. Java provides Random class that generates a random numbers. rand() gives long random numbers. srand() provides unique numbers.

Here is the source code of the Java Program to Use rand and srand Functions. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a sample program to generate a random numbers using rand() and srand()
  2. //rand() gives long random numbers
  3. //srand() provides unique numbers
  4. import java.util.Random;
  5. import java.util.UUID;
  6.  
  7. public class Rand_and_Srand 
  8. {
  9.     public static void main(String args[])
  10.     {
  11.         System.out.println("The numbers using rand");
  12.         for(int i=0; i<5; i++)
  13.         {
  14.             Random rand = new Random();
  15.             System.out.println(Math.abs(rand.nextInt()));
  16.         }
  17.  
  18.         System.out.println("The numbers using srand");
  19.         for(int i=0; i<5; i++)
  20.         {
  21.             System.out.println(Math.abs(UUID.randomUUID().getMostSignificantBits()));
  22.         }
  23.     }
  24. }

Output:

$ javac Rand_and_Srand.java
$ java Rand_and_Srand
 
The numbers using rand
1339557437
636169175
1207287888
1539694038
1040189301
The numbers using srand
301709257092546335
8798470719933102847
3480203219570178904
3272351410737399038
2158529096808811162

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.