Java provides classes to help you for generating random numbers. There are two ways you can generate random numbers using java.
The below examples show you how to create a random number and also help you to understand and use the code to generate random numbers in your application.
1. Random number in a specified range
Here you can specify the range within you want to generate the random numbers. Below code will explain you how to generate random numbers
import java.util.*;
public class RandomNumbers{ public static void main(String[] args){ Random random = new Random(); int randomNumber = random.nextInt(5); System.out.println(“Random Number between 0 to 5 : ” + randomNumber); } } |
Output:
Random Number between 0 to 5 : 1
2. Random number without specifying the range
import java.util.*;
public class RandomNumbers{ public static void main(String[] args){ Random random = new Random(); int randomNumber = random.nextInt(); System.out.println(“Random Number generated : ” + randomNumber); } } |
Output:
Random Number generated : -866975367
Leave a Reply