Skip to main content

Generate Random Integer in specific range in Java

Ranging random integers not found in java.util.Random

An example on generating random integers between a specified range.


import java.util.*;
class RandomRangeInt
public static void main(String args[])

// Create Random object
Random r=new Random();

// Specify start, end
int start=10;
int end=100;

// Create a 1 time loop
for(int i=0;i<1;i++)

// Generate random int below 100
int k=r.nextInt(end);

// If random integer below 100 is greater than start (10)

// Then print

                        // Else loop again, till if is true!, you may also write while loop
else i--;




If you want to include start i.e. you want to allow even value of start (here 10) to come, then you must change if(k>start) to if(k>=start)

If you don't wish to write the logic, you can see my example on my class gowtham.gutha.util.RandomRangeInteger, download the java-utils framework (for using the class).

If you don't have already seen generating random integers in Java, you can see my post of Generating random values in Java (for all datatypes int,float,long,double..) and for generating random strings from first and last names, there is also a post.


Popular posts from this blog

Setting Background Image in JFrame - Swing

Here is sample tutorial, a simple trick that enables you to set background image for JFrame.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame
JButton b1;
JLabel l1;
public BackgroundImageJFrame()
setTitle("Background Color for JFrame");
One way
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png")));
setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am …

Add two numbers in JSP easily

Here is an example on adding up two numbers in JSP. This is very simple as you see below. This requires very small piece of code. All i have done here is created a HTML file containing the input fields which contain the numbers to add up.Now the values in the input field are of type String, so i have done type casting and converted them into int using Integer.parseInt(). See how easy it looks.

Catch The Rat: Simple Game in Java

A simple, shortest and easiest game that could be written in Java using Swing components and event handling.