Why is "hello world" always printed on the source code below?
System.out.println(randomString(-229985452) + " " + randomString(-147909649));
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();
}
Random is an algorithm that generates an arbitrary number according to the seed value. So if the seeds are the same, the numbers are produced in the same pattern. Here, the seed value is -229985452 and new Random (-229985452).The number of occurrences of nextInt (27) is
8
5
12
12
15
0
This is what happens and new Random (-147909649).The number of occurrences in the nextInt (27) is
23
15
18
12
4
0
So, '`' is 96 for the ASCII code, and then you end up with 'hello world' as below.
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 --> d
© 2024 OneMinuteCode. All rights reserved.