WHY DOES THIS CODE USING RANDOM STRINGS PRINT “HELLO WORLD”?

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
Java 
 849  View(s)
Ratings:
Rate this:
I came across this piece of code, and found it rather interesting. The following print statement would print "hello world". Could anyone explain this?

System.out.println(randomString(-229985452) + " " + randomString(-147909649));
And randomString() 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();
}
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Why does this code using random strings print “hello world”?

    When an instance of java.util.Random is constructed with a specific seed parameter (in this case -229985452 or -147909649), it follows the random number generation algorithm beginning with that seed value.

    Every Random constructed with the same seed will generate the same pattern of numbers every time.

      Modified On Apr-09-2018 05:58:22 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!