beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java program to generate random number – Example

By Chaitanya Singh | Filed Under: Java Examples

Example Program to generate random numbers

In the below program, we are using the nextInt() method of Random class to serve our purpose.

/* Program: Random number generator
 * Written by: Chaitanya from beginnersbook.com
 * Input: None
 * Output:Random number between o and 200*/
import java.util.*;
class GenerateRandomNumber {
   public static void main(String[] args) {
      int counter;
      Random rnum = new Random();
      /* Below code would generate 5 random numbers
       * between 0 and 200.
       */
      System.out.println("Random Numbers:");
      System.out.println("***************");
      for (counter = 1; counter <= 5; counter++) {
         System.out.println(rnum.nextInt(200));
      }
   }
}

Output:

Random Numbers:
***************
135
173
5
17
15

The output of above program would not be same everytime. It would generate any 5 random numbers between 0 and 200 whenever you run this code. For e.g. When I ran it second time, it gave me the below output, which is entirely different from the above one.

Output 2:

Random Numbers:
***************
46
99
191
7
134

Enjoyed this post? Try these related posts

  1. Java Program to Calculate Simple Interest
  2. Java program to perform binary search – Example
  3. Java Program to find ASCII value of a Character
  4. Java Program to Count Vowels and Consonants in a String
  5. How To Convert Char To String and a String to char in Java
  6. Java Program to get input from user

Comments

  1. ASINGH says

    December 18, 2016 at 6:51 AM

    Anyone please tell me the algorithm for this program.

    Reply

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs

Java Examples

  • Check Odd-even
  • Linear Search
  • Binary Search
  • Floyd's Triangle
  • Reverse number
  • Random Number
  • first n prime numbers
  • Disp prime Numbers
  • Check Prime number
  • Palindrome String
  • Find factorial
  • Sum of elements of Array
  • Area of rectangle
  • Area of Square
  • Area of Triangle
  • Circle

Tutorials

  • Java Tutorial
  • OOPs Concepts
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap