nerdexam
Oracle

1Z0-811 · Question #68

Given the code fragment: Random r1 = new Random(10); Random r2 = new Random(10); // line n1 if (r1.nextInt() == r2.nextInt()) { System.out.println ("Jack"); } else { System.out.println ("Queen"); }…

The correct answer is A. A compilation error occurs at line n1. The stated correct answer (A) appears to be incorrect - this is a flawed question. new Random(10) is perfectly valid Java; the Random(long seed) constructor exists and the int literal 10 widens to long automatically, so no compilation error occurs at line n1. The real answer is…

Object-Oriented Programming Principles

Question

Given the code fragment: Random r1 = new Random(10); Random r2 = new Random(10); // line n1 if (r1.nextInt() == r2.nextInt()) { System.out.println ("Jack"); } else { System.out.println ("Queen"); } What is the result?

Options

  • AA compilation error occurs at line n1.
  • BJack
  • CThe program prints either Jack or Queen.
  • DQueen

How the community answered

(27 responses)
  • A
    89% (24)
  • B
    7% (2)
  • D
    4% (1)

Explanation

The stated correct answer (A) appears to be incorrect - this is a flawed question.

new Random(10) is perfectly valid Java; the Random(long seed) constructor exists and the int literal 10 widens to long automatically, so no compilation error occurs at line n1. The real answer is B (Jack). When two Random instances are created with the same seed (10), they produce an identical sequence of pseudo-random numbers - so r1.nextInt() and r2.nextInt() return the same value, making the == comparison true and printing "Jack".

Why the distractors fail:

  • C is wrong because the output is deterministic, not random - same seed always yields the same sequence.
  • D is wrong because the sequences are identical, so the else branch never executes.
  • A is wrong because new Random(long) is a valid constructor and 10 widens to long implicitly.

Memory tip: Think of a Random seed as a recipe - two cooks following the same recipe always produce the same dish. If you ever see two Random objects constructed with identical seeds, their outputs will match step-for-step.

Note for exam takers: If this appears on an official exam with answer A marked correct, flag it - the question likely contains an error. The Java Language Specification allows widening primitive conversion from int to long, making new Random(10) unambiguously valid.

Topics

#Random class seeding#Object instantiation#nextInt() behavior#Equality comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice