Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment

Back to Classroom

Random

Java Variables Course

Engineers From These Top Companies and Universities Trust EXLskills

1M+ Professionals | 100+ Institutions

This is the EXLskills free and open-source Java Variables Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java variables and operators.

Is this course FREE?

Yes, this a 100% free course that you can contribute to on GitHub here!

The random() method in the Math class returns a random number between 0.0 and 1.0, including 0.0 and not including 1.0, at random with uniform distribution from this range. This method is written like Math.random() and does not take in any parameters. The returns a double value. Run the program below to see the function. As you may suspect, you will get different numbers every time you run the program.

RandomMethodExample.java

package exlcode;
public class RandomMethodExample {
// Returns double value greater than or equal to 0.0 and less than 1.0
public static double exampleVariableOne = Math.random();
// Returns an integer value between 1 and 100
public static int exampleVariableTwo = (int) (Math.random() * 101);
public static void main(String[] args) {
System.out.println(exampleVariableOne);
System.out.println(exampleVariableTwo);
}
}

In order to increase our range from 0.0 to 100.0, we have to multiply the whole expression by 101 since the function's range is only 0.0 to 1.0. We then use casting to change the double to an int datatype value, which in turn truncates the decimal and gives us a whole number. There are different methods within the Random class which may be useful to you for various projects in the future.