generate short random number in java?

waqas picture waqas · Apr 17, 2012 · Viewed 11.9k times · Source

I want to generate a random number of type short exactly like there is a function for integer type called Random.nextInt(134116). How can I achieve it?

Answer

luketorjussen picture luketorjussen · Apr 17, 2012

There is no Random.nextShort() method, so you could use

short s = (short) Random.nextInt(Short.MAX_VALUE + 1);

The +1 is because the method returns a number up to the number specified (exclusive). See here

This will generate numbers from 0 to Short.MAX_VALUE inclusive (negative numbers were not requested by the OP)