This collection of 25 Java exercises covers everything from a basic bounded random integer to cryptographically secure tokens and biased probability sampling.
- You’ll practice generating bounded and unique values, secure OTPs and session tokens with
SecureRandom, random strings and strong passwords, reproducible sequences with a fixed seed, random dates, Fisher-Yates shuffling, weighted and biased random selection, Gaussian distributions, and thread-safe generation withThreadLocalRandom. - Later exercises apply the Stream API to random generation directly, filtering and collecting bounded
IntStreamvalues into sorted lists.
Each exercise includes a Problem Statement, Purpose, Hint, and a Solution with Explanation, with an alternative approach called out wherever a cleaner option exists.
- Also, See: Java Exercises with over 20+ topic-wise sets and 575+ coding questions to practice.
- Practice questions using our Online Java Compiler
+ Table of Contents (25 Exercises)
Table of contents
- Exercise 1: Divisible Random Integers
- Exercise 2: Unique Lottery Ticket Generator
- Exercise 3: Cryptographically Secure OTP
- Exercise 4: Random Character Selection
- Exercise 5: Random Fixed-Length String
- Exercise 6: Alphanumeric Password Generator
- Exercise 7: Multiplication of Random Floats
- Exercise 8: Secure Token & Hex Strings
- Exercise 9: Reproducible Dice Rolls (Seeding)
- Exercise 10: Random Date Generator
- Exercise 11: Shuffle an Array
- Exercise 12: Weighted Random Selection
- Exercise 13: Infinite Stream of Ints
- Exercise 14: Multithreaded Random Generation
- Exercise 15: Simulate a Coin Toss
- Exercise 16: Gaussian (Normal) Distribution
- Exercise 17: Unique Sub-sample Pick
- Exercise 18: Random RGB Color Generator
- Exercise 19: Random Enum Value Selection
- Exercise 20: Random UUID Generation
- Exercise 21: Generate 2D Matrix of Random Elements
- Exercise 22: Random Boolean with Custom Biasing
- Exercise 23: Pseudo-random Mock User Profile
- Exercise 24: Float Range Precision
- Exercise 25: Generate and Sort a Stream
Exercise 1: Divisible Random Integers
Problem Statement: Write a Java program to generate 3 random integers between 100 and 999 (inclusive) that are perfectly divisible by 5.
Purpose: This exercise helps you practice generating bounded random integers with Random.nextInt() and filtering values against a condition, a pattern commonly used when generating constrained test data.
Expected Output: Random numbers divisible by 5: [105, 780, 995] (values change on every run since they are random)
▼ Hint
- Use
random.nextInt(max - min + 1) + minto generate a number within a range. - Check divisibility using the modulo operator:
num % 5 == 0. - Keep generating numbers in a loop until you collect the required count.
- Store the qualifying numbers in a
List<Integer>so you can reuse the count and print them together.
▼ Solution & Explanation
Explanation:
random.nextInt(max - min + 1) + min: Shifts the random range so it falls between 100 and 999 inclusive.num % divisor == 0: Filters out numbers that are not multiples of 5.while (result.size() < count): Keeps generating numbers until exactly 3 qualifying values are collected.- Alternative: You could generate a multiple of 5 directly with
min + random.nextInt((max - min) / 5 + 1) * 5, which avoids the filtering loop entirely.
Exercise 2: Unique Lottery Ticket Generator
Problem Statement: Generate a List of 100 unique random lottery tickets. Each ticket number must be exactly 10 digits long. Once generated, randomly pick 2 winning tickets from the list.
Purpose: This exercise helps you practice enforcing uniqueness with a Set, building fixed-length digit strings, and using Collections.shuffle() to make a fair random selection, all common needs in simulations and raffle style systems.
Expected Output:
Total tickets generated: 100 Winning tickets: [4821093765, 9081726354]
▼ Hint
- Use a
LinkedHashSet<String>so duplicate tickets are rejected automatically while insertion order is kept. - Build each ticket by appending 10 random digits with
random.nextInt(10)in a loop. - Keep generating tickets until the set reaches the required size of 100.
- To pick winners fairly, copy the tickets into a
List, callCollections.shuffle(), then take the first 2 entries.
▼ Solution & Explanation
Explanation:
LinkedHashSet<String>: Rejects duplicate tickets automatically since aSetcannot contain repeated elements.ticket.append(random.nextInt(10)): Builds a 10 digit ticket number one digit at a time, so leading zeros are allowed and the length always stays fixed.Collections.shuffle(shuffled): Randomizes the order of the ticket list so the first entries can be treated as a fair random pick.- Alternative: You could pick winners without shuffling the whole list by generating random indices with
random.nextInt(tickets.size())and skipping duplicates.
Exercise 3: Cryptographically Secure OTP
Problem Statement: Write a utility method using SecureRandom to generate a 6-digit secure One-Time Password (OTP) for user authentication.
Purpose: This exercise helps you practice using SecureRandom instead of Random for security sensitive values, since SecureRandom produces output that is far harder to predict, which matters for authentication codes.
Expected Output: Your OTP is: 583920 (the digits change on every run)
▼ Hint
Use SecureRandom in place of Random, and append secureRandom.nextInt(10) to a StringBuilder once for each of the 6 digits.
▼ Solution & Explanation
Explanation:
SecureRandom: Uses a cryptographically strong random number generator, which is important whenever the output protects an account or a transaction.secureRandom.nextInt(10): Produces a single digit between 0 and 9 for each position of the OTP.otp.append(...): Builds the final OTP string digit by digit, preserving any leading zeros.- Alternative: You could generate a number with
secureRandom.nextInt(1_000_000)and pad it withString.format("%06d", value), though the digit by digit approach is easier to extend to other lengths.
Exercise 4: Random Character Selection
Problem Statement: Given the string String str = "JavaProgramming";, select a completely random character from it.
Purpose: This exercise helps you practice combining String.length() with Random.nextInt() to pick a valid random index, a pattern used whenever you need to sample from an existing collection of characters or elements.
Given Input: String str = "JavaProgramming";
Expected Output: Random character: g (varies on every run)
▼ Hint
Generate a random index between 0 (inclusive) and str.length() (exclusive) with random.nextInt(str.length()), then read the character at that index using str.charAt(index).
▼ Solution & Explanation
Explanation:
random.nextInt(str.length()): Generates an index that always stays within the valid bounds of the string.str.charAt(index): Retrieves the character sitting at the randomly chosen index.- Alternative: You could convert the string to a char array with
str.toCharArray()first and index into the array instead of callingcharAt(), which helps if you need to select multiple characters repeatedly.
Exercise 5: Random Fixed-Length String
Problem Statement: Write a method to generate a random string of length 7. The string must consist only of a mix of uppercase and lowercase alphabetic letters (no numbers or special symbols).
Purpose: This exercise helps you practice sampling characters from a fixed pool of allowed values, a technique that is the foundation for generating usernames, temporary codes, and other constrained random strings.
Expected Output: Random string: qXaZmoP (varies on every run)
▼ Hint
- Define a constant string containing all uppercase and lowercase letters.
- Loop 7 times, each time picking a random index into that constant with
random.nextInt(letters.length()). - Append each picked character to a
StringBuilderand return the final string.
▼ Solution & Explanation
Explanation:
LETTERS: Acts as the pool of allowed characters, restricted to uppercase and lowercase letters only.random.nextInt(LETTERS.length()): Picks a random position inside the pool for each character of the result.result.append(...): Builds the final string one randomly chosen letter at a time.- Alternative: You could use
random.ints()combined with streams to generate the string in a more compact, functional style.
Exercise 6: Alphanumeric Password Generator
Problem Statement: Create a strong password generator. The generated password must be 10 characters long and contain at least 2 uppercase letters, 2 lowercase letters, 2 digits, and 2 special characters.
Purpose: This exercise helps you practice satisfying multiple constraints at once when generating random data, and using Collections.shuffle() so the guaranteed characters do not always land in the same positions.
Expected Output: Generated password: Kd7#pQ2!mA (varies on every run)
▼ Hint
- First add 2 characters from each required pool (uppercase, lowercase, digits, special) into a
List<Character>. - Fill the remaining positions by picking random characters from a combined pool of all 4 categories.
- Call
Collections.shuffle()on the list before joining it into a string, so the guaranteed characters are not always grouped together.
▼ Solution & Explanation
Explanation:
passwordChars.add(...): Guarantees 2 characters from each required category before anything else is added.allChars: Combines every pool into one string so the remaining slots can be filled from any category.Collections.shuffle(passwordChars): Randomizes the character order so the guaranteed characters do not sit in predictable positions.- Alternative: You could validate a randomly generated 10 character string against the 4 rules in a loop, regenerating it until it passes, though the guaranteed insertion approach is more efficient.
Exercise 7: Multiplication of Random Floats
Problem Statement: Generate two random float values between 10.5 and 50.5. Calculate and print their multiplication product.
Purpose: This exercise helps you practice generating random floating point numbers within a custom range using Random.nextFloat(), since that method alone only returns values between 0.0 and 1.0.
Expected Output:
Number 1: 23.847391 Number 2: 41.192837 Product: 982.3765
▼ Hint
Scale random.nextFloat() to your range with the formula min + random.nextFloat() * (max - min), then call it once for each of the two numbers and multiply the results.
▼ Solution & Explanation
Explanation:
random.nextFloat(): Returns a value between 0.0 (inclusive) and 1.0 (exclusive), which acts as the base for the scaling formula.min + random.nextFloat() * (max - min): Stretches that 0 to 1 value across the 10.5 to 50.5 range.num1 * num2: Multiplies the two generated floats to get the final product.- Alternative: You could use
ThreadLocalRandom.current().nextFloat(min, max)(Java 17+) to get a bounded float directly, without writing the scaling formula yourself.
Exercise 8: Secure Token & Hex Strings
Problem Statement: Use SecureRandom to generate a secure random byte array of 32 bytes and convert it into a Hexadecimal string to act as a session token.
Purpose: This exercise helps you practice generating raw random bytes with SecureRandom.nextBytes() and converting binary data into a readable hexadecimal format, a common pattern for session tokens and API keys.
Expected Output: Session token: 9f3a1b7e2c4d8f0a6b5e9d3c1a7f4b8e2d6c0a9f3b7e1d5c8a2f6b0e4d9c3a17 (varies on every run)
▼ Hint
- Create a
byte[]array of the desired length and fill it withsecureRandom.nextBytes(array). - Loop over each byte and format it as a 2-digit hex value with
String.format("%02x", b). - Append each formatted value to a
StringBuilderto build the final token string.
▼ Solution & Explanation
Explanation:
secureRandom.nextBytes(tokenBytes): Fills the byte array with cryptographically strong random bytes in place.String.format("%02x", b): Converts a single byte into a 2-character hexadecimal representation, padding with a leading zero when needed.hexString.append(...): Concatenates each byte’s hex value into the final 64-character token string.- Alternative: You could use
Base64.getEncoder().encodeToString(tokenBytes)instead of hex encoding for a shorter token string.
Exercise 9: Reproducible Dice Rolls (Seeding)
Problem Statement: Write a program that simulates rolling a 6-sided die. Initialize the random generator with a specific seed value so that every time the program runs, it produces the exact same sequence of 5 numbers.
Purpose: This exercise helps you practice using a seeded Random instance to produce a reproducible sequence, which is useful for debugging, testing, and simulations where results need to be repeatable.
Expected Output: Dice rolls: 1 5 2 6 4 (this exact sequence repeats every time the program runs with the same seed)
▼ Hint
Pass a fixed long value into the Random constructor, like new Random(42L), instead of leaving it unseeded. The same seed always produces the same sequence of nextInt() calls.
▼ Solution & Explanation
Explanation:
new Random(seed): Initializes the generator with a fixed starting state, so it always produces the same sequence of values for a given seed.random.nextInt(6) + 1: Produces a value between 1 and 6 to represent a die face.results[i] = ...: Stores each roll in order so the full sequence can be printed at the end.- Alternative: You could seed a shared
Randomfield once in the class instead of passing the seed into the method, if multiple methods in the same program need the same reproducible sequence.
Exercise 10: Random Date Generator
Problem Statement: Write a program to generate a random date between January 1, 2020, and December 31, 2025.
Purpose: This exercise helps you practice working with LocalDate and epoch days, converting a date range into a numeric range so a random value can be mapped back to a valid calendar date.
Expected Output: Random date: 2023-07-14 (varies on every run)
▼ Hint
- Convert both boundary dates to epoch days using
LocalDate.toEpochDay(). - Pick a random epoch day between the start and end values.
- Convert the random epoch day back into a date with
LocalDate.ofEpochDay().
▼ Solution & Explanation
Explanation:
startDate.toEpochDay(): Converts the date into the number of days since January 1, 1970, giving a numeric value that random math can work with.startEpochDay + (long) (random.nextDouble() * (endEpochDay - startEpochDay)): Scales a random fraction across the day range to land on a random epoch day between the two dates.LocalDate.ofEpochDay(randomEpochDay): Converts the random epoch day back into a proper calendar date.- Alternative: You could pick a random year, month, and day separately and validate the combination, but working in epoch days avoids having to handle invalid dates like February 30.
Exercise 11: Shuffle an Array
Problem Statement: Given an integer array int[] arr = {10, 20, 30, 40, 50, 60};, write an algorithm to shuffle its elements randomly in-place.
Purpose: This exercise helps you practice the Fisher-Yates shuffle algorithm, an efficient in-place technique for randomizing the order of elements in an array without allocating extra memory.
Given Input: int[] arr = {10, 20, 30, 40, 50, 60};
Expected Output: Shuffled array: [40, 10, 60, 20, 50, 30] (order changes on every run)
▼ Hint
- Walk the array backward, from the last index down to index 1.
- At each position
i, pick a random indexjbetween 0 andiinclusive withrandom.nextInt(i + 1). - Swap the elements at positions
iandjbefore moving to the next index.
▼ Solution & Explanation
Explanation:
for (int i = arr.length - 1; i > 0; i--): Walks the array from the end toward the start, shrinking the unshuffled portion by one each time.random.nextInt(i + 1): Picks a random index from the remaining unshuffled portion, including the current position.- swap logic: Exchanges the values at
iandjso the element atiis finalized with a randomly chosen value. - Alternative: You could wrap the array in a
List<Integer>withArrays.asList()and callCollections.shuffle(), though that involves boxing each primitive int.
Exercise 12: Weighted Random Selection
Problem Statement: You have three items with different probabilities of being picked: Gold (70% chance), Silver (20% chance), and Bronze (10% chance). Write a function that returns an item according to its specified weight over 1,000 iterations.
Purpose: This exercise helps you practice mapping ranges of a random number to outcomes with different probabilities, a pattern used in loot systems, A/B testing, and weighted sampling.
Expected Output:
Gold: 702 Silver: 198 Bronze: 100
▼ Hint
- Generate a random integer between 0 and 99 with
random.nextInt(100). - Map the value to Gold if it falls below 70, Silver if it falls below 90, and Bronze otherwise.
- Repeat the pick 1,000 times and track the counts in a
Map<String, Integer>.
▼ Solution & Explanation
Explanation:
random.nextInt(100): Produces a value between 0 and 99, which acts as a percentile roll.roll < 70: Covers 70 out of 100 possible values, giving Gold a 70 percent chance of being picked.roll < 90: Covers the next 20 values (70 through 89), giving Silver a 20 percent chance.- Alternative: You could build a cumulative weight table and use binary search to find the matching item, which scales better when there are many weighted items instead of just three.
Exercise 13: Infinite Stream of Ints
Problem Statement: Use Java 8 streams (java.util.Random.ints()) to generate an infinite stream of random numbers between 1 and 100, filter out the odd numbers, and print the first 10 even numbers.
Purpose: This exercise helps you practice combining Random.ints() with stream operations like filter() and limit() to process an unbounded sequence of random values lazily.
Expected Output: 42 88 16 54 20 76 2 60 34 98 (varies on every run)
▼ Hint
Call random.ints(1, 101) to get an infinite IntStream bounded between 1 and 100, chain .filter(n -> n % 2 == 0) to keep only even numbers, then use .limit(10) before printing, since the stream itself never ends.
▼ Solution & Explanation
Explanation:
random.ints(1, 101): Produces an unboundedIntStreamof values between 1 (inclusive) and 101 (exclusive)..filter(n -> n % 2 == 0): Keeps only the even numbers as the stream is consumed..limit(10): Stops the otherwise infinite stream once 10 matching values have been produced.- Alternative: You could call
.boxed().collect(Collectors.toList())instead offorEach()if you need the 10 even numbers stored in a list rather than printed directly.
Exercise 14: Multithreaded Random Generation
Problem Statement: Write a program where 3 concurrent threads simultaneously generate random numbers. Use ThreadLocalRandom to ensure thread safety and avoid performance bottlenecks.
Purpose: This exercise helps you practice generating random numbers safely across multiple threads, since sharing a single Random instance between threads causes contention while ThreadLocalRandom avoids it entirely.
Expected Output:
Thread-1 generated: 47 Thread-2 generated: 83 Thread-3 generated: 12
▼ Hint
- Call
ThreadLocalRandom.current()inside each thread rather than sharing oneRandominstance across them. - Wrap the number generation logic in a method that each
Threadruns independently. - Call
join()on every thread frommain()so the program waits for all 3 to finish before exiting.
▼ Solution & Explanation
Explanation:
ThreadLocalRandom.current(): Returns aRandominstance scoped to the calling thread, so no two threads ever contend for the same generator.new Thread(() -> generateInThread(...)): Starts a separate thread that runs the number generation logic independently.t1.join(): Blocks the main thread until the given thread has completed, ensuring all output is printed before the program exits.- Alternative: You could submit the 3 tasks to an
ExecutorServiceinstead of managing rawThreadobjects, which scales better if the number of concurrent tasks grows.
Exercise 15: Simulate a Coin Toss
Problem Statement: Write a program to simulate a coin toss (Heads/Tails) 10,000 times. Print the total count and percentage distribution of Heads and Tails.
Purpose: This exercise helps you practice using Random.nextBoolean() to model a binary outcome and aggregating repeated trials into a percentage distribution, a common pattern in Monte Carlo style simulations.
Expected Output:
Heads: 5012 (50.12%) Tails: 4988 (49.88%)
▼ Hint
Call random.nextBoolean() once per toss, treat true as Heads and false as Tails, then divide each count by the total number of tosses and multiply by 100 to get the percentage.
▼ Solution & Explanation
Explanation:
random.nextBoolean(): Returnstrueorfalsewith roughly equal probability, modeling a fair coin toss.(heads * 100.0) / totalTosses: Converts the raw count into a percentage, using100.0to force floating point division.for (int i = 0; i < totalTosses; i++): Repeats the toss the requested number of times, accumulating the totals as it goes.- Alternative: You could use
random.ints(totalTosses, 0, 2)as a stream and count the zeros and ones withCollectors.groupingBy()instead of a manual loop.
Exercise 16: Gaussian (Normal) Distribution
Problem Statement: Generate 5 random double numbers representing a normal (Gaussian) distribution with a mean of 0.0 and a standard deviation of 1.0.
Purpose: This exercise helps you practice using Random.nextGaussian() and scaling its output to a custom mean and standard deviation, which is useful whenever simulated data needs to cluster around a center value instead of being uniformly spread.
Expected Output:
0.4536201 -1.2098765 0.0871234 1.5432190 -0.3345678
▼ Hint
random.nextGaussian() already returns values centered on a mean of 0.0 with a standard deviation of 1.0, so scale it with the formula mean + stdDev * random.nextGaussian() to support any target mean and spread.
▼ Solution & Explanation
Explanation:
random.nextGaussian(): Returns a random double drawn from a standard normal distribution, meaning it is centered at 0.0 with a standard deviation of 1.0.mean + stdDev * random.nextGaussian(): Shifts and stretches the standard normal value to match the requested mean and standard deviation.double[] values = new double[count]: Stores each generated value so all 5 numbers can be printed after the loop finishes.- Alternative: You could generate the values as a stream with
random.doubles(count).map(...), applying the scaling formula inside themap()call.
Exercise 17: Unique Sub-sample Pick
Problem Statement: Given a list of 20 distinct city names, write a program to randomly select a unique subset of 4 cities without repeating any city.
Purpose: This exercise helps you practice sampling a fixed number of unique elements from an existing collection using Collections.shuffle(), a pattern commonly used for random quizzes, giveaways, and test data sampling.
Expected Output: Selected cities: [Pune, Tokyo, Jaipur, Sydney] (varies on every run)
▼ Hint
Copy the city list into a new mutable List, call Collections.shuffle() on the copy, then use subList(0, 4) to take the first 4 entries as your unique random sample.
▼ Solution & Explanation
Explanation:
new ArrayList<>(cities): Copies the original list so the source data is never modified by the shuffle.Collections.shuffle(shuffled): Randomizes the order of all 20 cities in place.shuffled.subList(0, sampleSize): Takes the first 4 cities from the shuffled list, which is equivalent to a unique random sample since no city can appear twice in the source list.- Alternative: You could use a
LinkedHashSet<String>and keep adding random elements from the source list until it reaches size 4, relying on the set to reject duplicates automatically.
Exercise 18: Random RGB Color Generator
Problem Statement: Write a method to generate a random color formatted as a valid Hex color code string (e.g., #3F51B5) by generating random values for Red, Green, and Blue channels.
Purpose: This exercise helps you practice generating bounded random integers for each color channel and formatting them into a hexadecimal string, a pattern used in UI theming, data visualization, and design tools.
Expected Output: Random color: #3F51B5 (varies on every run)
▼ Hint
Generate 3 separate random integers between 0 and 255 with random.nextInt(256), one for each of the Red, Green, and Blue channels, then combine them using String.format("#%02X%02X%02X", red, green, blue).
▼ Solution & Explanation
Explanation:
random.nextInt(256): Produces a value between 0 and 255, matching the valid range for a single color channel.String.format("#%02X%02X%02X", ...): Formats each channel as a 2-digit uppercase hexadecimal value and joins them behind a leading#.%02X: Pads single-digit hex values with a leading zero so every channel always contributes exactly 2 characters.- Alternative: You could generate a single random integer between 0 and 16,777,215 (0xFFFFFF) and convert it directly with
Integer.toHexString(), though padding short results still needs extra handling.
Exercise 19: Random Enum Value Selection
Problem Statement: Define an enum called Weekday containing all seven days. Write a program to pick a completely random day from the enum.
Purpose: This exercise helps you practice combining Enum.values() with Random.nextInt() to select a random constant, a pattern useful whenever you need to sample from a fixed, predefined set of options.
Expected Output: Random day: THURSDAY (varies on every run)
▼ Hint
Call Weekday.values() to get an array of all 7 enum constants, generate a random index with random.nextInt(days.length), then use that index to read a constant from the array.
▼ Solution & Explanation
Explanation:
Weekday.values(): Returns an array containing all 7 constants defined in the enum, in the order they were declared.random.nextInt(days.length): Generates a random index that always stays within the bounds of thedaysarray.days[random.nextInt(days.length)]: Reads the enum constant sitting at the randomly chosen index.- Alternative: You could cache the result of
Weekday.values()in a static field instead of calling it on every invocation, since the method allocates a new array each time it is called.
Exercise 20: Random UUID Generation
Problem Statement: Generate a unique Cryptographically Secure universally unique identifier (UUID) variant 4 using Java’s built-in libraries.
Purpose: This exercise helps you practice using UUID.randomUUID() to produce a version 4 UUID backed by a cryptographically strong random source, which is the standard approach for generating unique identifiers for database records, sessions, and API resources.
Expected Output: Generated UUID: 3f29a1d4-8b7c-4e21-9f56-2c8a7d4e1b3f (varies on every run)
▼ Hint
Java’s UUID class already provides UUID.randomUUID(), which internally uses SecureRandom to generate a version 4 UUID, so there is no need to build the identifier manually.
▼ Solution & Explanation
Explanation:
UUID.randomUUID(): Generates a type 4 (randomly generated) UUID using a cryptographically strong pseudo-random number generator internally.- version 4: Means 122 of the 128 bits are random, while the remaining bits are fixed to identify the UUID version and variant.
UUIDreturn type: Keeps the identifier as a properUUIDobject instead of a plain string, so it can be compared, stored, or converted later using the class’s own methods.- Alternative: You could build a UUID manually from 16 random bytes generated with
SecureRandom, thoughUUID.randomUUID()already handles the version and variant bits correctly and is far less error-prone.
Exercise 21: Generate 2D Matrix of Random Elements
Problem Statement: Write a program to fill a 4×4 two-dimensional integer array with random numbers ranging from -50 to 50.
Purpose: This exercise helps you practice generating bounded random values that include negative numbers, and filling a two-dimensional array using nested loops, a pattern common in grid based simulations and image or matrix processing.
Expected Output:
[12, -34, 45, -7] [-22, 3, 50, -49] [8, -15, 27, -1] [-40, 19, -33, 6]
▼ Hint
- Create a
4x4array withint[][] matrix = new int[4][4];. - Use two nested
forloops to visit every row and column. - Fill each cell with
random.nextInt(max - min + 1) + min, using -50 and 50 as the bounds so negative values are included.
▼ Solution & Explanation
Explanation:
new int[rows][cols]: Allocates a two-dimensional array with the requested number of rows and columns, each cell initialized to 0.random.nextInt(max - min + 1) + min: Generates a value between -50 and 50 inclusive for each cell, since shifting byminallows the range to cover negative numbers.- nested
forloops: Visits every row and every column exactly once, guaranteeing all 16 cells are filled. - Alternative: You could flatten the fill logic using
Arrays.stream(matrix).forEach(row -> Arrays.setAll(row, i -> random.nextInt(101) - 50))for a more compact, stream based approach.
Exercise 22: Random Boolean with Custom Biasing
Problem Statement: Create a method getRandomBooleanWithBias(double probabilityOfTrue) that returns true or false based on a bias configuration (e.g., if passing 0.85, it should return true 85% of the time).
Purpose: This exercise helps you practice converting a continuous random value from Random.nextDouble() into a biased boolean outcome, a pattern used in feature flags, probability based game mechanics, and simulations that need a skewed coin flip.
Expected Output: True percentage: 84.7% (varies slightly on every run, but stays close to 85%)
▼ Hint
random.nextDouble() returns a value between 0.0 (inclusive) and 1.0 (exclusive), so comparing it with < probabilityOfTrue makes the method return true for exactly that proportion of calls on average.
▼ Solution & Explanation
Explanation:
random.nextDouble(): Produces a uniformly distributed value between 0.0 and 1.0, which makes it suitable for probability comparisons.random.nextDouble() < probabilityOfTrue: Returnstruewhenever the generated value falls below the bias threshold, so a higherprobabilityOfTruenaturally yieldstruemore often.trueCount * 100.0 / totalRuns: Confirms the bias is working as expected by measuring the observed percentage oftrueresults across many trials.- Alternative: You could throw an
IllegalArgumentExceptionifprobabilityOfTruefalls outside the 0.0 to 1.0 range, which guards the method against misuse in a larger codebase.
Exercise 23: Pseudo-random Mock User Profile
Problem Statement: Write a mock data generator that outputs a randomized user profile containing a random name from an array, a random age between 18 and 65, and a random boolean status indicating if they are active.
Purpose: This exercise helps you practice combining several random generation techniques, array indexing, bounded integers, and booleans, into a single realistic object, a common need when seeding test databases or building demo data.
Expected Output: Name: Rohan, Age: 34, Active: true (varies on every run)
▼ Hint
- Store a set of candidate names in a
String[]array and pick one usingrandom.nextInt(names.length). - Generate the age with
random.nextInt(65 - 18 + 1) + 18so it always falls between 18 and 65 inclusive. - Use
random.nextBoolean()for the active status, then combine all 3 values into a single formatted string.
▼ Solution & Explanation
Explanation:
NAMES[random.nextInt(NAMES.length)]: Picks a random name from the fixed pool of candidate names.random.nextInt(65 - 18 + 1) + 18: Shifts the generated value so the age always lands between 18 and 65 inclusive.random.nextBoolean(): Produces a randomtrueorfalseto represent whether the mock user is active.- Alternative: You could return a small record or class instead of a formatted string, which keeps the name, age, and active status as typed fields for use elsewhere in a larger mock data pipeline.
Exercise 24: Float Range Precision
Problem Statement: Generate 10 random floating-point values strictly between 0.001 and 0.009 and print them formatted to exactly four decimal places.
Purpose: This exercise helps you practice generating random values inside a very narrow range and controlling their display precision with printf, which matters whenever raw floating point output is too noisy to read directly.
Expected Output:
0.0034 0.0071 0.0025 0.0088 0.0019 0.0056 0.0043 0.0067 0.0031 0.0079
▼ Hint
Reuse the same scaling formula from the earlier float range exercise, min + random.nextFloat() * (max - min), with 0.001f and 0.009f as the bounds, then print each value with System.out.printf("%.4f%n", value) to force exactly 4 decimal places.
▼ Solution & Explanation
Explanation:
min + random.nextFloat() * (max - min): Scales the 0.0 to 1.0 range ofnextFloat()down into the narrow 0.001 to 0.009 window.System.out.printf("%.4f%n", value): Formats the float to exactly 4 digits after the decimal point, rounding as needed, followed by a platform correct newline.for (int i = 0; i < 10; i++): Repeats the generation and formatting step 10 times to produce the full list of values.- Alternative: You could use a
DecimalFormat("0.0000")instance instead ofprintf, which is convenient if the same formatting pattern needs to be reused across many parts of a larger program.
Exercise 25: Generate and Sort a Stream
Problem Statement: Using Java Streams, generate 15 random integers between 50 and 150, sort them in descending order, and collect them into a List.
Purpose: This exercise helps you practice chaining Random.ints() with stream operations like sorted() and collect() to turn a bounded random sequence into a finished, ordered List in a single pipeline.
Expected Output: Sorted numbers: [148, 139, 127, 121, 110, 98, 95, 88, 79, 74, 68, 63, 59, 55, 51] (varies on every run)
▼ Hint
- Use
random.ints(count, min, max + 1)to generate exactly 15 bounded values as anIntStream. - Call
.boxed()to convert the primitive stream into aStream<Integer>so it can be sorted with aComparator. - Sort with
Comparator.reverseOrder()and finish with.collect(Collectors.toList()).
▼ Solution & Explanation
Explanation:
random.ints(count, min, max + 1): Produces a finiteIntStreamof exactly 15 values, each between 50 and 150 inclusive..boxed(): Converts each primitiveintinto anIntegerobject, which is required before sorting with aComparator..sorted(Comparator.reverseOrder()): Orders the boxed values from highest to lowest.- Alternative: You could collect the values first with
.collect(Collectors.toList())and then sort the resulting list in place usinglist.sort(Comparator.reverseOrder()), though keeping the sort inside the stream pipeline avoids a separate mutation step.

Leave a Reply