Problem of the Day
Monday, June 1, 2026
Problem:
An Array of dogNames has been declared and initialized as follows:
String[] dogNames = {"Rover","Fido","Daisy","Spot","Sparky","Skippy","Bowser","Lola"};Which of the following will correctly identify a random name from the Array?
dogNames[(int) Math.random() * dogNames.length]dogNames[(int) (Math.random() * dogNames.length )]dogNames[(int) (Math.random() * dogNames.length - 1)]dogNames[(int) (Math.random() * dogNames.length + 1)]dogNames[(int) (Math.random() * (dogNames.length - 1))]
The correct answer is b. The Math.random() call gets a value from 0 - 0.999..., and multiplying it by the length of dogNames, 8, yields a value from 0 - 7.9999... Casting that as an int gives us an integer in the range 0 - 7 inclusive, which will correctly identify an in-bounds index from the Array.