This question already has an answer here:
- Why does this code using random strings print “hello world”? 14 answers
The following simple program in Java uses the java.util.Random
class such that it always displays "hello world". The code snippet can be seen below.
package nomain;
import java.util.Random;
final public class J
{
public static String randomString(int seed)
{
Random rand = new Random(seed);
StringBuilder sb = new StringBuilder();
for(int i=0;;i++)
{
int n=rand.nextInt(27);
if (n==0)
{
break;
}
sb.append((char) ('`'+n));
}
return sb.toString();
}
public static void main(String args[])
{
System.out.println(randomString(-229985452)+' '+randomString(-147909649));
}
}
There is some surprise in that it always displays "hello world" even if the Random class is used that causes the random numbers to generate hence, the numbers should be changed on each run and the corresponding characters should be changed accordingly but it always displays only one stable string which is as mentioned above "hello world". Why does it happen?