This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Why does the following use randomly generated text produce “Hello world”?

Why is “Hello world” printed with the following randomly generated text? Can someone explain that?

System.out.println(randomString(-229985452) + " " + randomString(-147909649));
Copy the code

The randomString() method mentioned above looks like this:

public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    while (true)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}
Copy the code

Answer 1:

When an instance of java.util.Random is constructed with a specific “seed parameter” (in this case -229985452 or -147909649), it follows a Random number generation algorithm starting from that seed value. That is, if the “seeds” of random classes are the same, they will generate the same set of numbers.

Hot discussion:

If modulo 27 is taken for each element of the random number sequence, there are six elements each in “hello\0” and “world\0”. If you assume a true Random class, the chance of getting the sequence you want is 1 in 27^6 (i.e., 1 in 387420489) — pretty impressive, but just a little boring!

Answer 2:

While other answers answer the “why,” here’s how:

Give an example of the Random class:

Random r = new Random(-229985452)
Copy the code

The first six digits generated by calling R.nextint (27) are:

23, 15, 18, 12, 4, 0Copy the code

Add each generated number to the integer representation of the character ‘(that is, 96) to get the corresponding English letter:

8 + 96 = 104 --> h 5 + 96 = 101 --> e 12 + 96 = 108 --> l 12 + 96 = 108 --> l 15 + 96 = 111 --> o 23 + 96 = 119 --> w 15  + 96 = 111 --> o 18 + 96 = 114 --> r 12 + 96 = 108 --> l 4 + 96 = 100 --> dCopy the code

Reference:

Stack Overflow :Why does this code use random strings print “Hello world”?