Java/Random numbers

From Meshplex

Jump to: navigation, search
Image:Java_programming.jpg
Introduction to Java
Overview of Java
How to Setup Java on your PC
Java Data Types, Variables,and Arrays
Operators
Java Packages, Classes, and Interfaces
Java Program
Java Modifiers
Java Control Statements
Java Exception Handling
Java Object Oriented Programming
Java Wrappers
Java Strings
Java Math
Java Arrays
Java Random Numbers
Java Date and Time
Java Regular Expressions
Java Java Collections
Java Generics
Java Thread and Multithreading
Java IO and file Handling
Java Network Programming
Java RMI
Java Image, Audio, Video
Java GUI
Java Applets
Java Internationalization
Java JDBC
Java and XML

[edit] Java Random Numbers

Java provides one utility class called Random. This class mainly used to generate random numbers. This class is very much useful for an application that selects a winner randomly. This class can also be used to generate random passwords. I mainly use this class for "Forgot your Password" section.


The below example will generate random number ten times and every time it will generate a different number between 0 and 50.

import java.util.Random;
 
public class RandomNumberExample {
 
  public static void main(String[] args) {
 
    Random randomNumber = new Random( System.currentTimeMillis() );
 
    for (int i = 0; i < 10; i++) {
      System.out.println(randomNumber.nextInt(50));
    }
 
  }
 
}

[edit] How to create Random passwords

If you are looking for an example to generate a random password then below example will help you. In this example the word range will be 0-9, A-Z and a-z. Since we want the combination of this characters, we have put a condition where we are checking for the integer value to be in range of 48 - 57 or 65 - 90 or 97 - 122. These integer values represents the ASCII values for the above word range.

Please refer the ASCII chart.

import java.util.Random;
 
public class RandomPassword {
 
  public static void main(String[] args) {
 
    Random randomNumber = new Random();
 
    char password[] = new char[15];
 
    for (int i = 0; i < 15;) {
 
      int value = randomNumber.nextInt(125);
      System.out.println(value);
      if ((value >= 48 && value <= 57) || (value >= 65 && value <= 90)
          || (value >= 97 && value <= 122)) {
 
        password[i] = (char) value;
        i++;
      }
    }
    System.out.println("Your password is " + new String(password));
  }
}