javarandomshort

generate short random number in java?


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?


Solution

  • 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)