Using the Random Class
generate a random number is to use the Java Random class of the java.util package. It generates a stream of pseudorandom numbers. We can generate a random number of any data type, such as integer, float, double, Boolean, long. If you are going to use this class to generate random numbers, follow the steps given below:
- First, import the class java.lang.Random.
- Create an object of the Random class. Why (TBD)
- Invoke any of the following methods:
- nextInt()
- nextFloat()
- nextDouble()
- nextLong()
- nextBoolean()
Example: Using Java Random Class
First, we will see the implementation using java.util.Random – Assume we need to generate 10 digit random number in Java between 0 to 100.
import java.util.Random;
public class RandomNumbers{
public static void main(String[] args) {
Random objGenerator = new Random();
for (int iCount = 0; iCount< 10; iCount++){
int randomNumber = objGenerator.nextInt(100);
System.out.println("Random No : " + randomNumber);
}
}
}
Output:
Random No : 17
Random No : 57
Random No : 73
Random No : 48
Random No : 68
Random No : 86
Random No : 34
Random No : 97
Random No : 73
Random No : 18
program-2
import java.util.Random;
class AtRandomNumber
{
public static void main(String[] args)
{
Random random = new Random();
int rand = 0;
while (true){
rand = random.nextInt(11);
if(rand !=0)
break;
}
System.out.println(rand);
}
}
output
6
The now() method of the Localdate class returns the Date object representing the current time.The now() method of LocalDate class
import java.time.LocalDate;
public class CreateDate {
public static void main(String args[]) {
LocalDate date = LocalDate.now();
System.out.println("Current Date: "+date);
}
}
Output
Current Date: 2020-11-08
reference:
https://www.tutorialspoint.com/how-to-get-the-current-date-in-java
https://www.w3schools.in/java/examples/generate-random-numbers
https://www.tutorialspoint.com/using-predefined-class-name-as-class-or-variable-name-in-java
Leave a comment