Java Programming Fundamentals: Practical Exercises for Beginners

When entering the world of Java programming, a solid foundation is the first step toward success. To help you build a strong programming basse, we've designed a series of Java fundamental exercises aimed at mastering the core concepts and programming techniques of the language.

Whether you're a beginner or a developer looking to strengthen your fundamentals, these exercises cover the most critical aspects of Java programming, from variables and data types to flow control and array operations, ensuring you gradually build solid coding skills and problem-solving abilities.

By participating in our fundamental exercises, you'll have the oppportunity to:

  • Understand Java's basic syntax and programming conventions;
  • Master variable definition and usage, along with data type conversions;
  • Become familiar with flow control statements like conditionals and loops;
  • Learn array creation, manipulation, and common algorithm applications.

Below are five exercises that you can imagine as levels in a game. First, read the requirements, then try to write the code yourself to see if you can meet them. Afterward, compare your solution with the provided example code. All examples are ready to run.

Table of Contents

Comprehensive Exercises

I. Airfare Calculator

II. Prime Number Identifier

III. Array Duplication

IV. Judge Scoring System

V. Verification Code Generator

VI. Number Encryption

Comprehensive Exercises

I. Airfare Calculator

Requirement: Calculate airline ticket prices based on peak/off-peak seasons and cabin class. Input the original ticket price, month, and cabin class (first class or economy). Calculate the final ticket price according to these rules: Peak season (May-October): first class at 90% discount, economy at 85% discount. Off-peak season (November-April): first class at 70% discount, economy at 65% discount.

public static void calculateAirfare() {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter original ticket price: ");
    double originalPrice = input.nextDouble();
    System.out.print("Enter travel month: ");
    int travelMonth = input.nextInt();
    System.out.print("Enter cabin class (first/economy): ");
    cabinClass = input.next();

    double discountRate = 1.0;
    
    if (isPeakSeason(travelMonth)) {
        discountRate = cabinClass.equals("first") ? 0.9 : 0.85;
    } else {
        discountRate = cabinClass.equals("first") ? 0.7 : 0.65;
    }

    double finalPrice = originalPrice * discountRate;
    System.out.printf("Final ticket price: $%.2f%n", finalPrice);
}

private static boolean isPeakSeason(int month) {
    return month >= 5 && month <= 10;
}

II. Prime Number Identifier

Requirement: Count how many prime numbers exist between 101 and 200, and display all of them.

public static void findPrimeNumbers() {
    int primeCount = 0;
    List<Integer> primes = new ArrayList<>();
    
    for (int currentNum = 101; currentNum <= 200; currentNum++) {
        if (isPrimeNumber(currentNum)) {
            primes.add(currentNum);
            primeCount++;
        }
    }
    
    System.out.println("Found " + primeCount + " prime numbers:");
    for (int i = 0; i < primes.size(); i++) {
        System.out.print(primes.get(i) + (i % 10 == 9 ? "\n" : " "));
    }
}

private static boolean isPrimeNumber(int number) {
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;
    
    for (int divisor = 3; divisor <= Math.sqrt(number); divisor += 2) {
        if (number % divisor == 0) {
            return false;
        }
    }
    return true;
}

III. Array Duplication

Requirement: Copy elements from one array to a new array.

public static void duplicateArray() {
    // Define original array
    int[] sourceArray = {1, 2, 3, 4, 5};
    
    // Create destination array with same length
    int[] destinationArray = new int[sourceArray.length];
    
    // Copy elements using System.arraycopy
    System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
    
    // Display the copied array
    System.out.println("Original array: " + Arrays.toString(sourceArray));
    System.out.println("Copied array: " + Arrays.toString(destinationArray));
}

IV. Judge Scoring System

Requirement: In a singing competition, 6 judges score a contestant. Scores are integers between 0-100. The final score is the average of the 4 middle scores after removing the highest and lowest scores. Implement this process to calculate the contestant's final score.

Analysis:

  1. Input six integers between 0-100 as judge scores
  2. Traverse the array to find highest and lowest scores
  3. Create a new array excluding the highest and lowest scores
  4. Calculate the average of the remaining scores
public static void calculateFinalScore() {
    // Input six scores between 0-100
    int[] scores = new int[6];
    Scanner input = new Scanner(System.in);
    
    for (int i = 0; i < scores.length; ) {
        System.out.println("Enter judge score #" + (i + 1) + ":");
        int currentScore = input.nextInt();
        if (currentScore >= 0 && currentScore <= 100) {
            scores[i] = currentScore;
            i++;
        } else {
            System.out.println("Invalid input. Please enter a score between 0 and 100.");
        }
    }

    // Find highest and lowest scores
    ScoreStats stats = calculateScoreStats(scores);
    
    // Calculate average of middle scores
    double total = 0;
    int count = 0;
    
    for (int score : scores) {
        if (score != stats.maxScore && score != stats.minScore) {
            total += score;
            count++;
        }
    }
    
    double finalScore = total / count;
    System.out.printf("Contestant's final score: %.2f%n", finalScore);
}

private static ScoreStats calculateScoreStats(int[] scores) {
    ScoreStats stats = new ScoreStats();
    stats.maxScore = scores[0];
    stats.minScore = scores[0];
    
    for (int score : scores) {
        if (score > stats.maxScore) {
            stats.maxScore = score;
        }
        if (score < stats.minScore) {
            stats.minScore = score;
        }
    }
    
    return stats;
}

private static class ScoreStats {
    int maxScore;
    int minScore;
}

V. Verification Code Generator

Requirement: Create a method to generate a random 5-character verification code. The format should be: first four characters are uppercase or lowercase letters, last character is a digit.

public static void generateVerificationCode() {
    // Create a character set containing all uppercase and lowercase letters
    String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    Random random = new Random();
    
    // Build the first four characters
    StringBuilder codeBuilder = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        int randomIndex = random.nextInt(letters.length());
        codeBuilder.append(letters.charAt(randomIndex));
    }
    
    // Add the final digit
    codeBuilder.append(random.nextInt(10));
    
    // Display the verification code
    System.out.println("Verification code: " + codeBuilder.toString());
}

VI. Number Encryption

Requirement: A system needs to encrypt a positive number (e.g., 1983) for transmission.

Encryption rules:

  1. Extract each digit
  2. Add 5 to each digit
  3. Take modulo 10 of each result
  4. Reverse the entire sequence of digits

Analysis:

  1. Determine the length of the number
  2. Create an array to store each digit
  3. Store each digit in the array
  4. Add 5 to each digit
  5. Apply modulo 10 to each digit
  6. Reverse the array
  7. Combine digits into final number
  8. Display the encrypted password
public static void encryptNumber() {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a number to encrypt:");
    int originalNumber = input.nextInt();
    
    // Convert number to digit array
    int[] digits = extractDigits(originalNumber);
    
    // Apply encryption transformation
    for (int i = 0; i < digits.length; i++) {
        digits[i] = (digits[i] + 5) % 10;
    }
    
    // Reverse the digit array
    reverseArray(digits);
    
    // Convert back to number
    int encryptedNumber = digitsToInt(digits);
    
    System.out.println("Encrypted number: " + encryptedNumber);
}

private static int[] extractDigits(int number) {
    // Count digits
    int digitCount = 0;
    int temp = number;
    while (temp != 0) {
        temp /= 10;
        digitCount++;
    }
    
    // Extract digits into array
    int[] digits = new int[digitCount];
    temp = number;
    for (int i = digitCount - 1; i >= 0; i--) {
        digits[i] = temp % 10;
        temp /= 10;
    }
    
    return digits;
}

private static void reverseArray(int[] array) {
    for (int i = 0, j = array.length - 1; i < j; i++, j--) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

private static int digitsToInt(int[] digits) {
    int result = 0;
    for (int digit : digits) {
        result = result * 10 + digit;
    }
    return result;
}

Each exercise focuses on practical applications and educational value, with detailed guidance and examples to help you transition from theory to practice. Whether your goal is to enhance professional skills or explore the joy of programming, we invite you to join our exercises and explore the mysteries of Java programming together!

Tags: java Programming Exercises algorithms Arrays Number Theory

Posted on Tue, 30 Jun 2026 16:39:12 +0000 by sjaccaud