How to generate random integers within a specific range in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How to generate random integers within a specific range in Java?

How do I generate a random int value in a specific range? I have tried the following, but those do not work:

29th Dec 2018, 10:26 PM
Sonu Kumar
Sonu Kumar - avatar
5 Answers
+ 4
Yah
30th Dec 2018, 5:52 AM
Sonu Kumar
Sonu Kumar - avatar
+ 3
just noting, Satish Kumar 's code would generate a random number from 0 to 9. you can also use the Math.random() function without needing to import anything. It generates a random number between 0-.9999... (int) Math.random()*11 would give an integer from 0-10
30th Dec 2018, 5:50 AM
Asirap
+ 3
(int)(Math.random() * 10) //Random int from 0 to 9 (int)(Math.random() * 10) + 1 //Random int from 1 to 10
30th Dec 2018, 1:44 PM
Shuaib Nuruddin
Shuaib Nuruddin - avatar
+ 2
import java.util.Random; class Demo{ public static void main(String[] args){ Random r=new Random(); int i=r.nextInt(10); System.out.print(i); } } You can specify the range at the place of 10
29th Dec 2018, 10:39 PM
Satish Kumar
Satish Kumar - avatar