Written by Sai Sandeep Thota on August 20, 2013 in Java > Programming

Java Program to Generate a Random Number

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this article we are going to write a Java Program to generate a random number. Java has an inbuilt method to generate random number i.e., random() which generates a random number between 0 and a specified number.

In the program below we are defining a class called randGen, in it we are declaring three variables randNum to store random number, a[] an array, arrayLen to store the length of array. Java allows you to find the Length of array without writing lines of code by simply using array.length.

We are using Math.random() * arrayLen to generate a random number between 0 and length of the array – 1. We are using (int) to force the result to be in integer in-order to eliminate decimals or floating points, so we are using this type casting.

Then we are printing the list of elements present in the array and element present at random position.

import java.util.*;

class randGen {
	public static void main(String args[])
	{
		int randNum;
		int a[] = {1,2,3,445,3,12,43,32,22};
		int arrayLen = a.length;
		randNum = (int) (Math.random() * arrayLen);
		System.out.println("Number of elements in the Array: " + arrayLen);
		System.out.println("Elements in the Array: ");
		for(int i=0;i<arrayLen;i++)
		{
			System.out.print(a[i] + "\t");
		}
		System.out.println();	
		System.out.println("Random Number generated between 0 and " + arrayLen + " is: " + randNum);
		System.out.println("Element at " + randNum + " position is: " + a[randNum]);
	}
}

Output:
generate_random_number_java

In the above program we are printing element at random position in an array, if you want to just generate a random number, you can use the following code:

import java.util.*;

class random {
	public static void main(String args[])
	{
		int rand = (int)(Math.random() * 100);
		System.out.println("Random Number:" + rand);
	}
}

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: