Building the Password

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

Probably. My taste is to build the string in three steps.

Building the Password

Next, the program builds the password:

    String password = "";
    int j = 0;
    
    while ( j<digits )
    {
      password = password + choices.charAt( rand.nextInt( choices.length() ) );
      j = j + 1;
    }

First the password is initialized to the empty string. Then random characters, selected from choices, are appended to it, one-by-one. The expression

rand.nextInt( choices.length() )

randomly picks an integer from 0 up to (but not including) the length of the choices string. Then that integer is used to select a character from the choices string. Say that the random integer were X. Then

choices.charAt( X )

is character number X in the string choices, where counting starts at zero. This character is appended to the password and the loop repeats. (For more about string methods, see chapter 29.)

QUESTION 16:

About four things happen in one statement, in the above. This can be hard to keep track of. Is the following code fragment equivalent?

    String password = "";
    int j = 0;
    while ( j<digits )
     {
      int range = choices.length();
      int characterNumber = rand.nextInt( range );
      char ch = choices.charAt( characterNumber );
      password = password + ch;
      j = j + 1;
    }