Fundamentals 5 min read

Why a Java Program Using Random with Fixed Seeds Always Prints "Hello world"

Although the program uses java.util.Random with different seed values, each execution prints the same 'Hello world' because the Random instances are initialized with fixed seeds, causing the pseudo‑random generator to produce identical sequences that map to the characters forming the phrase.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Why a Java Program Using Random with Fixed Seeds Always Prints "Hello world"

This article examines a Java program that appears to generate random strings but consistently outputs the phrase "Hello world".

import java.util.*; public class HelloWorld{ public static String randomString(int i){ Random ran = new Random(i); StringBuilder sb = new StringBuilder(); for (int n = 0; ; n++){ int k = ran.nextInt(27); if (k == 0) break; sb.append((char)('`' + k)); } return sb.toString(); } public static void main(String[] args){ System.out.println(randomString(-229985452)+" "+randomString(-147909649)); } }

The key point is that each Random object is created with a specific integer seed (‑229985452 and ‑147909649). In Java, a Random instance seeded with the same value will generate the same sequence of numbers on every run, because the algorithm is deterministic.

For the first seed the generated numbers are 8 5 12 12 15 0 ; for the second seed they are 23 15 18 12 4 0 . Each number k is added to the ASCII code of the back‑tick character ( '`' , value 96) and cast to a character, producing the letters h‑e‑l‑l‑o‑w‑o‑r‑l‑d, i.e., "Hello world".

Thus the program always prints the same result, illustrating the concept of pseudo‑random numbers: when the seed is fixed, the output is predictable. The article also references the original Stack Overflow discussion and notes that this behavior is a classic example of deterministic pseudo‑random generation in computer science.

javaProgrammingRandomPseudo‑randomseed
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.