how to use Random class using collections in java
Previous | Home | Next |
In this example we will show you how to use the Random class.
For using the Random class first of all we have import the java.util package in which the java.util.Random class is contained. We have created a class named CollectionExample in which we have created an object of the Random class and performed various operations.
In the following example we have created an object of the Random class using its default constructor as,
Random rndm=new Random();
This method creates a new random number generator.
We have also used the nextInt() method of the Random which is having the following syntax,
int nextInt(int val)
The above method returns a pseudorandom, uniformly distributed int value between 0 and specified value in the method, drawn from the current random number generator's sequence.
In this example we have created a class named CollectionExample inside which we have created a Random class object named rndm. Then we have taken an integer type variable named number to hold the random values generated by the method nextInt(int val) on the object of the Random class i.e rndm(in this example), then we have displayed some strings using if-else condition.
package r4r.co.in;
import java.util.*;
public class CollectionExample
{
/**
* @param args
*/
public static void main(String args[]) throws IllegalArgumentException
{
try
{
Random rndm=new Random(); // creates an object of Random class
int numbers; // created a variable named numbers of integer type
numbers=rndm.nextInt(4)+1; // assigning the random numbers generated between 0-4 to numbers
System.out.println(numbers); // displaying the number generated
if(numbers==4) // if number generated equals to 4 then
{
System.out.println("hi!!!!!!!"); // print hi!!!!!!
}
else
{
System.out.println("bye!!!!!!!"); // otherwise print bye!!!!!!!
}
}
catch(IllegalArgumentException e)
{
e.printStackTrace();
}
}
}
The above example gives the following output:
2
bye!!!!!!!
4
hi!!!!!!!
Previous | Home | Next |