How to Get Random Integers in Java


In this example we will show three different methods to generate random integers in Java.

Source Code

1) Using Math.random()

package com.beginner.examples;

public class RandomExample1 {

	public static void main(String[] args) {

		int min = 10;
		int max = 100;
		int random = (int)(1+Math.random()*(max-min+1));
		System.out.println(random);
    }
}

Output:

53

2) Using java.util.Random

package com.beginner.examples;

import java.util.Random;

public class RandomExample2 {

	public static void main(String[] args) {

		int min = 10;
		int max = 100;
		Random r = new Random();
		int random = r.nextInt((max - min) + 1) + min;
		System.out.println(random);
    }
}

Output:

61

3) Using System.currentTimeMillis()

package com.beginner.examples;

public class RandomExample3 {

	public static void main(String[] args) {

		int min = 10;
		int max = 100;
		long randomNum = System.currentTimeMillis();  
		int random = (int)(randomNum%(max-min)+min);  
		System.out.println(random);
    }
}

Output:

27

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments