PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Online Compilers▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Java Exercises » Java Random Data Generation Exercises: 25 Coding Problems with Solutions

Java Random Data Generation Exercises: 25 Coding Problems with Solutions

Updated on: July 6, 2026 | Leave a Comment

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 with ThreadLocalRandom.
  • Later exercises apply the Stream API to random generation directly, filtering and collecting bounded IntStream values 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) + min to 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
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

    public static List<Integer> generateDivisibleRandoms(int min, int max, int divisor, int count) {
        Random random = new Random();
        List<Integer> result = new ArrayList<>();
        while (result.size() < count) {
            int num = random.nextInt(max - min + 1) + min;
            if (num % divisor == 0) {
                result.add(num);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // Usage:
        List<Integer> numbers = generateDivisibleRandoms(100, 999, 5, 3);
        System.out.println("Random numbers divisible by 5: " + numbers);
    }
}Code language: Java (java)

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, call Collections.shuffle(), then take the first 2 entries.
▼ Solution & Explanation
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class Main {

    public static List<String> generateUniqueTickets(int totalTickets, int digitLength) {
        Set<String> tickets = new LinkedHashSet<>();
        Random random = new Random();
        while (tickets.size() < totalTickets) {
            StringBuilder ticket = new StringBuilder();
            for (int i = 0; i < digitLength; i++) {
                ticket.append(random.nextInt(10));
            }
            tickets.add(ticket.toString());
        }
        return new ArrayList<>(tickets);
    }

    public static List<String> pickWinners(List<String> tickets, int winnerCount) {
        List<String> shuffled = new ArrayList<>(tickets);
        Collections.shuffle(shuffled);
        return shuffled.subList(0, winnerCount);
    }

    public static void main(String[] args) {
        // Usage:
        List<String> tickets = generateUniqueTickets(100, 10);
        List<String> winners = pickWinners(tickets, 2);
        System.out.println("Total tickets generated: " + tickets.size());
        System.out.println("Winning tickets: " + winners);
    }
}Code language: Java (java)

Explanation:

  • LinkedHashSet<String>: Rejects duplicate tickets automatically since a Set cannot 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
import java.security.SecureRandom;

public class Main {

    public static String generateOtp(int length) {
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder otp = new StringBuilder();
        for (int i = 0; i < length; i++) {
            otp.append(secureRandom.nextInt(10));
        }
        return otp.toString();
    }

    public static void main(String[] args) {
        // Usage:
        String otp = generateOtp(6);
        System.out.println("Your OTP is: " + otp);
    }
}Code language: Java (java)

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 with String.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
import java.util.Random;

public class Main {

    public static char getRandomCharacter(String str) {
        Random random = new Random();
        int index = random.nextInt(str.length());
        return str.charAt(index);
    }

    public static void main(String[] args) {
        String str = "JavaProgramming";
        // Usage:
        char randomChar = getRandomCharacter(str);
        System.out.println("Random character: " + randomChar);
    }
}Code language: Java (java)

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 calling charAt(), 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 StringBuilder and return the final string.
▼ Solution & Explanation
import java.util.Random;

public class Main {

    private static final String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(LETTERS.length());
            result.append(LETTERS.charAt(index));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        // Usage:
        String randomString = generateRandomString(7);
        System.out.println("Random string: " + randomString);
    }
}Code language: Java (java)

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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Main {

    private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL = "!@#$%^&*";

    public static String generatePassword(int length) {
        Random random = new Random();
        List<Character> passwordChars = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            passwordChars.add(UPPER.charAt(random.nextInt(UPPER.length())));
            passwordChars.add(LOWER.charAt(random.nextInt(LOWER.length())));
            passwordChars.add(DIGITS.charAt(random.nextInt(DIGITS.length())));
            passwordChars.add(SPECIAL.charAt(random.nextInt(SPECIAL.length())));
        }

        String allChars = UPPER + LOWER + DIGITS + SPECIAL;
        while (passwordChars.size() < length) {
            passwordChars.add(allChars.charAt(random.nextInt(allChars.length())));
        }

        Collections.shuffle(passwordChars);

        StringBuilder password = new StringBuilder();
        for (char c : passwordChars) {
            password.append(c);
        }
        return password.toString();
    }

    public static void main(String[] args) {
        // Usage:
        String password = generatePassword(10);
        System.out.println("Generated password: " + password);
    }
}Code language: Java (java)

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
import java.util.Random;

public class Main {

    public static float getRandomFloat(float min, float max) {
        Random random = new Random();
        return min + random.nextFloat() * (max - min);
    }

    public static void main(String[] args) {
        // Usage:
        float num1 = getRandomFloat(10.5f, 50.5f);
        float num2 = getRandomFloat(10.5f, 50.5f);
        float product = num1 * num2;

        System.out.println("Number 1: " + num1);
        System.out.println("Number 2: " + num2);
        System.out.println("Product: " + product);
    }
}Code language: Java (java)

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 with secureRandom.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 StringBuilder to build the final token string.
▼ Solution & Explanation
import java.security.SecureRandom;

public class Main {

    public static String generateSecureToken(int byteLength) {
        SecureRandom secureRandom = new SecureRandom();
        byte[] tokenBytes = new byte[byteLength];
        secureRandom.nextBytes(tokenBytes);

        StringBuilder hexString = new StringBuilder();
        for (byte b : tokenBytes) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        // Usage:
        String token = generateSecureToken(32);
        System.out.println("Session token: " + token);
    }
}Code language: Java (java)

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
import java.util.Random;

public class ReproducibleDiceRoll {

    public static int[] rollDice(long seed, int rolls) {
        Random random = new Random(seed);
        int[] results = new int[rolls];
        for (int i = 0; i < rolls; i++) {
            results[i] = random.nextInt(6) + 1;
        }
        return results;
    }

    public static void main(String[] args) {
        // Usage:
        int[] rolls = rollDice(42L, 5);
        System.out.print("Dice rolls: ");
        for (int roll : rolls) {
            System.out.print(roll + " ");
        }
    }
}Code language: Java (java)

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 Random field 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
import java.time.LocalDate;
import java.util.Random;

public class Main {

    public static LocalDate generateRandomDate(LocalDate startDate, LocalDate endDate) {
        long startEpochDay = startDate.toEpochDay();
        long endEpochDay = endDate.toEpochDay();
        Random random = new Random();
        long randomEpochDay = startEpochDay + (long) (random.nextDouble() * (endEpochDay - startEpochDay));
        return LocalDate.ofEpochDay(randomEpochDay);
    }

    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2020, 1, 1);
        LocalDate end = LocalDate.of(2025, 12, 31);
        // Usage:
        LocalDate randomDate = generateRandomDate(start, end);
        System.out.println("Random date: " + randomDate);
    }
}Code language: Java (java)

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 index j between 0 and i inclusive with random.nextInt(i + 1).
  • Swap the elements at positions i and j before moving to the next index.
▼ Solution & Explanation
import java.util.Arrays;
import java.util.Random;

public class Main {

    public static void shuffleArray(int[] arr) {
        Random random = new Random();
        for (int i = arr.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50, 60};
        // Usage:
        shuffleArray(arr);
        System.out.println("Shuffled array: " + Arrays.toString(arr));
    }
}Code language: Java (java)

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 i and j so the element at i is finalized with a randomly chosen value.
  • Alternative: You could wrap the array in a List<Integer> with Arrays.asList() and call Collections.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
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Main {

    public static String pickWeightedItem(Random random) {
        int roll = random.nextInt(100);
        if (roll < 70) {
            return "Gold";
        } else if (roll < 90) {
            return "Silver";
        } else {
            return "Bronze";
        }
    }

    public static void main(String[] args) {
        Random random = new Random();
        Map<String, Integer> counts = new HashMap<>();
        counts.put("Gold", 0);
        counts.put("Silver", 0);
        counts.put("Bronze", 0);

        // Usage:
        for (int i = 0; i < 1000; i++) {
            String item = pickWeightedItem(random);
            counts.put(item, counts.get(item) + 1);
        }

        System.out.println("Gold: " + counts.get("Gold"));
        System.out.println("Silver: " + counts.get("Silver"));
        System.out.println("Bronze: " + counts.get("Bronze"));
    }
}Code language: Java (java)

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
import java.util.Random;

public class Main {

    public static void printFirstTenEvens() {
        Random random = new Random();
        random.ints(1, 101)
              .filter(n -> n % 2 == 0)
              .limit(10)
              .forEach(n -> System.out.print(n + " "));
    }

    public static void main(String[] args) {
        // Usage:
        printFirstTenEvens();
    }
}Code language: Java (java)

Explanation:

  • random.ints(1, 101): Produces an unbounded IntStream of 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 of forEach() 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 one Random instance across them.
  • Wrap the number generation logic in a method that each Thread runs independently.
  • Call join() on every thread from main() so the program waits for all 3 to finish before exiting.
▼ Solution & Explanation
import java.util.concurrent.ThreadLocalRandom;

public class Main {

    public static void generateInThread(String threadName) {
        int value = ThreadLocalRandom.current().nextInt(1, 101);
        System.out.println(threadName + " generated: " + value);
    }

    public static void main(String[] args) throws InterruptedException {
        // Usage:
        Thread t1 = new Thread(() -> generateInThread("Thread-1"));
        Thread t2 = new Thread(() -> generateInThread("Thread-2"));
        Thread t3 = new Thread(() -> generateInThread("Thread-3"));

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();
    }
}Code language: Java (java)

Explanation:

  • ThreadLocalRandom.current(): Returns a Random instance 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 ExecutorService instead of managing raw Thread objects, 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
import java.util.Random;

public class Main {

    public static void simulateTosses(int totalTosses) {
        Random random = new Random();
        int heads = 0;
        int tails = 0;

        for (int i = 0; i < totalTosses; i++) {
            if (random.nextBoolean()) {
                heads++;
            } else {
                tails++;
            }
        }

        double headsPercent = (heads * 100.0) / totalTosses;
        double tailsPercent = (tails * 100.0) / totalTosses;

        System.out.println("Heads: " + heads + " (" + headsPercent + "%)");
        System.out.println("Tails: " + tails + " (" + tailsPercent + "%)");
    }

    public static void main(String[] args) {
        // Usage:
        simulateTosses(10000);
    }
}Code language: Java (java)

Explanation:

  • random.nextBoolean(): Returns true or false with roughly equal probability, modeling a fair coin toss.
  • (heads * 100.0) / totalTosses: Converts the raw count into a percentage, using 100.0 to 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 with Collectors.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
import java.util.Random;

public class Main {

    public static double[] generateGaussianValues(double mean, double stdDev, int count) {
        Random random = new Random();
        double[] values = new double[count];
        for (int i = 0; i < count; i++) {
            values[i] = mean + stdDev * random.nextGaussian();
        }
        return values;
    }

    public static void main(String[] args) {
        // Usage:
        double[] values = generateGaussianValues(0.0, 1.0, 5);
        for (double value : values) {
            System.out.println(value);
        }
    }
}Code language: Java (java)

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 the map() 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {

    public static List<String> pickRandomCities(List<String> cities, int sampleSize) {
        List<String> shuffled = new ArrayList<>(cities);
        Collections.shuffle(shuffled);
        return shuffled.subList(0, sampleSize);
    }

    public static void main(String[] args) {
        List<String> cities = Arrays.asList(
                "Mumbai", "Delhi", "Bengaluru", "Chennai", "Kolkata",
                "Pune", "Hyderabad", "Ahmedabad", "Jaipur", "Lucknow",
                "London", "Paris", "Tokyo", "Berlin", "Madrid",
                "Toronto", "Sydney", "Dubai", "Singapore", "New York"
        );

        // Usage:
        List<String> selectedCities = pickRandomCities(cities, 4);
        System.out.println("Selected cities: " + selectedCities);
    }
}Code language: Java (java)

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
import java.util.Random;

public class Main {

    public static String generateRandomHexColor() {
        Random random = new Random();
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return String.format("#%02X%02X%02X", red, green, blue);
    }

    public static void main(String[] args) {
        // Usage:
        String hexColor = generateRandomHexColor();
        System.out.println("Random color: " + hexColor);
    }
}Code language: Java (java)

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
import java.util.Random;

enum Weekday {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {

    public static Weekday getRandomDay() {
        Weekday[] days = Weekday.values();
        Random random = new Random();
        return days[random.nextInt(days.length)];
    }

    public static void main(String[] args) {
        // Usage:
        Weekday randomDay = getRandomDay();
        System.out.println("Random day: " + randomDay);
    }
}Code language: Java (java)

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 the days array.
  • 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
import java.util.UUID;

public class Main {

    public static UUID generateSecureUuid() {
        return UUID.randomUUID();
    }

    public static void main(String[] args) {
        // Usage:
        UUID uuid = generateSecureUuid();
        System.out.println("Generated UUID: " + uuid);
    }
}Code language: Java (java)

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.
  • UUID return type: Keeps the identifier as a proper UUID object 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, though UUID.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 4x4 array with int[][] matrix = new int[4][4];.
  • Use two nested for loops 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
import java.util.Arrays;
import java.util.Random;

public class Main {

    public static int[][] generateMatrix(int rows, int cols, int min, int max) {
        Random random = new Random();
        int[][] matrix = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = random.nextInt(max - min + 1) + min;
            }
        }
        return matrix;
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        // Usage:
        int[][] matrix = generateMatrix(4, 4, -50, 50);
        printMatrix(matrix);
    }
}Code language: Java (java)

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 by min allows the range to cover negative numbers.
  • nested for loops: 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
import java.util.Random;

public class Main  {

    public static boolean getRandomBooleanWithBias(double probabilityOfTrue) {
        Random random = new Random();
        return random.nextDouble() < probabilityOfTrue;
    }

    public static void main(String[] args) {
        // Usage:
        int trueCount = 0;
        int totalRuns = 1000;
        for (int i = 0; i < totalRuns; i++) {
            if (getRandomBooleanWithBias(0.85)) {
                trueCount++;
            }
        }
        System.out.println("True percentage: " + (trueCount * 100.0 / totalRuns) + "%");
    }
}Code language: Java (java)

Explanation:

  • random.nextDouble(): Produces a uniformly distributed value between 0.0 and 1.0, which makes it suitable for probability comparisons.
  • random.nextDouble() < probabilityOfTrue: Returns true whenever the generated value falls below the bias threshold, so a higher probabilityOfTrue naturally yields true more often.
  • trueCount * 100.0 / totalRuns: Confirms the bias is working as expected by measuring the observed percentage of true results across many trials.
  • Alternative: You could throw an IllegalArgumentException if probabilityOfTrue falls 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 using random.nextInt(names.length).
  • Generate the age with random.nextInt(65 - 18 + 1) + 18 so 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
import java.util.Random;

public class Main {

    private static final String[] NAMES = {"Aarav", "Isha", "Rohan", "Meera", "Kabir", "Diya"};

    public static String generateUserProfile() {
        Random random = new Random();
        String name = NAMES[random.nextInt(NAMES.length)];
        int age = random.nextInt(65 - 18 + 1) + 18;
        boolean isActive = random.nextBoolean();
        return "Name: " + name + ", Age: " + age + ", Active: " + isActive;
    }

    public static void main(String[] args) {
        // Usage:
        String profile = generateUserProfile();
        System.out.println(profile);
    }
}Code language: Java (java)

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 random true or false to 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
import java.util.Random;

public class Main {

    public static float getRandomFloat(float min, float max) {
        Random random = new Random();
        return min + random.nextFloat() * (max - min);
    }

    public static void main(String[] args) {
        // Usage:
        for (int i = 0; i < 10; i++) {
            float value = getRandomFloat(0.001f, 0.009f);
            System.out.printf("%.4f%n", value);
        }
    }
}Code language: Java (java)

Explanation:

  • min + random.nextFloat() * (max - min): Scales the 0.0 to 1.0 range of nextFloat() 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 of printf, 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 an IntStream.
  • Call .boxed() to convert the primitive stream into a Stream<Integer> so it can be sorted with a Comparator.
  • Sort with Comparator.reverseOrder() and finish with .collect(Collectors.toList()).
▼ Solution & Explanation
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

public class Main {

    public static List<Integer> generateSortedDescending(int count, int min, int max) {
        Random random = new Random();
        return random.ints(count, min, max + 1)
                     .boxed()
                     .sorted(Comparator.reverseOrder())
                     .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        // Usage:
        List<Integer> sortedNumbers = generateSortedDescending(15, 50, 150);
        System.out.println("Sorted numbers: " + sortedNumbers);
    }
}Code language: Java (java)

Explanation:

  • random.ints(count, min, max + 1): Produces a finite IntStream of exactly 15 values, each between 50 and 150 inclusive.
  • .boxed(): Converts each primitive int into an Integer object, which is required before sorting with a Comparator.
  • .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 using list.sort(Comparator.reverseOrder()), though keeping the sort inside the stream pipeline avoids a separate mutation step.

Filed Under: Java Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Java Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Java Exercises
TweetF  sharein  shareP  Pin

  Java Exercises

  • All Java Exercises
  • Java Exercise for Beginners
  • Java Loops Exercise
  • Java String Exercise
  • Java ArrayList Exercise
  • Java LinkedList Exercise
  • Java HashMap and TreeMap Exercise
  • Java HashSet and TreeSet Exercise
  • Java OOP Exercise
  • Java Methods Exercise
  • Java Enums Exercise
  • Java Exception Handling Exercise
  • Java File Handling Exercise
  • Java Date and Time Exercise
  • Java Data Structures Exercise
  • Java Sorting and Searching Exercise
  • Java Lambda and Functional Interfaces Exercise
  • Java Regex Exercise
  • Java Random Data Generation Exercise
  • Java Generics Exercise
  • Java Reflection Exercise
  • Java JDBC Exercise

All Coding Exercises

Python Exercises C Exercises C++ Exercises Java Exercises C# Exercises

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com