Java Program to Generate Random Numbers - The Coding Shala
Home >> Java Programs >> Java Program to generate random numbers
Other Posts You May Like
In this post, we will learn how to Generate Random Numbers in Java.
Java Program to Generate Random Numbers
Write a Java Program to Generate random integers and doubles.
Approach 1
We can generate random integers using the Random class and nextInt() method. To generate random double use nextDouble() method.
Java Program:
import java.util.*; class Solution { public static void main(String[] args) { //create object of Random class Random rand = new Random(); //random integers System.out.println("Random integer is: " + rand.nextInt()); System.out.println("Random integer is: " + rand.nextInt()); System.out.println("Random integer between 0 to 500 is: " + rand.nextInt(500)); System.out.println("Random integer between 0 to 500 is: " + rand.nextInt(500)); //random doubles System.out.println("Random double is: " + rand.nextDouble()); System.out.println("Random double is: " + rand.nextDouble()); } }
Output:
Random integer is: -237602665 Random integer is: 1724780755 Random integer between 0 to 500 is: 200 Random integer between 0 to 500 is: 374 Random double is: 0.0422535568322393 Random double is: 0.10644146580779246
Approach 2
We can also use Math.random() to generate double random numbers. It will return values between 0.0 to 1.0.
Java Program:
import java.util.*; class Solution { public static void main(String[] args) { //using Math.random() System.out.println("Random double is: " + Math.random()); System.out.println("Random double is: " + Math.random()); System.out.println("Random double is: " + Math.random()); System.out.println("Random double is: " + Math.random()); } }
Output:
Random double is: 0.4970007856549141 Random double is: 0.2711311270754778 Random double is: 0.1275856087981624 Random double is: 0.37157351525839033
- Java Program to Sort an Array in Ascending Order
- Java Program to Multiply Two Numbers
- Java Program to Swap Two Numbers
- Java Program to Reverse a String
- Java Program to find Sum of Digits of a Number
Comments
Post a Comment