Java Strings- Practice Programs with Solutions

 


//1. Reverse a String


import java.util.Arrays;


public class StringReverse {


    public static void main(String[] args) {

        String original = "welcome";

        

        // Method 1 - Using length() and charAt()

        String rev1 = "";

        for (int i = original.length() - 1; i >= 0; i--) {

            rev1 += original.charAt(i);

        }

        System.out.println("Method 1 - Reverse string: " + rev1);

        

        // Method 2 - By converting string to char array

        String rev2 = "";

        char[] charArray = original.toCharArray(); // Convert string to character array

        System.out.println("Character array: " + Arrays.toString(charArray)); // Display the character array

        

        for (int i = charArray.length - 1; i >= 0; i--) {

            rev2 += charArray[i];

        }

        System.out.println("Method 2 - Reverse string: " + rev2);

        

        // Method 3 - Using StringBuffer

        StringBuffer sb = new StringBuffer(original);

        String rev3 = sb.reverse().toString();

        System.out.println("Method 3 - Reverse string: " + rev3);

        

        // Method 4 - Using StringBuilder

        StringBuilder sbuilder = new StringBuilder(original);

        String rev4 = sbuilder.reverse().toString();

        System.out.println("Method 4 - Reverse string: " + rev4);

    }

}



//2. Check if a String is Palindrome


public class PalindromeCheck {

    public static void main(String[] args) {

        String str = "madam";

        String reversed = new StringBuilder(str).reverse().toString();

        if (str.equals(reversed)) {

            System.out.println(str + " is a palindrome.");

        } else {

            System.out.println(str + " is not a palindrome.");

        }

    }

}


//3. Count Vowels and Consonants


public class VowelConsonantCount {

    public static void main(String[] args) {

        String str = "hello";

        int vowels = 0, consonants = 0;

        str = str.toLowerCase();

        for (char c : str.toCharArray()) {

            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {

                vowels++;

            } else {

                consonants++;

            }

        }

        System.out.println("Vowels: " + vowels);

        System.out.println("Consonants: " + consonants);

    }

}


//4. Find the Length of a String Without Using length() Method


public class StringLength {

    public static void main(String[] args) {

        String str = "hello";

        int length = 0;

        for (char c : str.toCharArray()) {

            length++;

        }

        System.out.println("Length of String: " + length);

    }

}


//5. Convert a String to Upper Case


public class ToUpperCase {

    public static void main(String[] args) {

        String str = "hello";

        String upperCaseStr = str.toUpperCase();

        System.out.println("Uppercase: " + upperCaseStr);

    }

}


//6. Convert a String to Lower Case


public class ToLowerCase {

    public static void main(String[] args) {

        String str = "HELLO";

        String lowerCaseStr = str.toLowerCase();

        System.out.println("Lowercase: " + lowerCaseStr);

    }

}


//7. Replace a Character in a String


public class ReplaceCharacter {

    public static void main(String[] args) {

        String str = "hello";

        String replacedStr = str.replace('l', 'y');

        System.out.println("Replaced String: " + replacedStr);

    }

}


//8. Remove All White Spaces from a String


public class RemoveSpaces {

    public static void main(String[] args) {

        String str = "he llo world";

        String noSpacesStr = str.replaceAll("\\s", "");

        System.out.println("String without spaces: " + noSpacesStr);

    }

}



//9. Check if Two Strings are Anagrams


import java.util.Arrays;

public class AnagramCheck {

    public static void main(String[] args) {

        String str1 = "listen";

        String str2 = "silent";

        

        char[] arr1 = str1.toCharArray();

        char[] arr2 = str2.toCharArray();

        

        Arrays.sort(arr1);

        Arrays.sort(arr2);

        

        if (Arrays.equals(arr1, arr2)) {

            System.out.println(str1 + " and " + str2 + " are anagrams.");

        } else {

            System.out.println(str1 + " and " + str2 + " are not anagrams.");

        }

    }

}




//10. Split a String into an Array


import java.util.Arrays;


public class SplitString {

    public static void main(String[] args) {

        String str = "hello world";

        String[] words = str.split(" ");

        System.out.println(Arrays.toString(words));

    }

}


//11. Remove a Specific Character from a String


public class RemoveCharacter {

    public static void main(String[] args) {

        String str = "hello";

        String removedStr = str.replace("l", "");

        System.out.println("String after removing 'l': " + removedStr);

    }

}




//12. Concatenate Two Strings Without Using + Operator


public class ConcatenateStrings {

    public static void main(String[] args) {

        String str1 = "hello";

        String str2 = "world";

        String concatenatedStr = str1.concat(str2);

        System.out.println("Concatenated String: " + concatenatedStr);

    }

}



//13. Reverse Words in a Sentence


public class ReverseWords {

    public static void main(String[] args) {

        String str = "hello world";

        String[] words = str.split(" ");

        StringBuilder reversedStr = new StringBuilder();

        

        for (int i = words.length - 1; i >= 0; i--) {

            reversedStr.append(words[i]).append(" ");

        }

        

        System.out.println("Reversed Sentence: " + reversedStr.toString().trim());

    }

}


Java Arrays - Practice Programs with Solutions


 /////////////////////  SINGLE DIMENSIONAL ARRAYS - SOLUTIONS ////////////////



// 1. Find the Largest Element in an Array


public class LargestElement {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int largest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] > largest) {

                largest = numbers[i];

            }

        }

        System.out.println("Largest Element: " + largest);

    }

}



// 2. Find the Smallest Element in an Array


public class SmallestElement {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int smallest = numbers[0];

        for (int i = 1; i < numbers.length; i++) {

            if (numbers[i] < smallest) {

                smallest = numbers[i];

            }

        }

        System.out.println("Smallest Element: " + smallest);

    }

}


//3. Calculate the Sum of All Elements in an Array


public class ArraySum {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        System.out.println("Sum of Elements: " + sum);

    }

}



//4. Calculate the Average of All Elements in an Array


public class ArrayAverage {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        double average = (double) sum / numbers.length;

        System.out.println("Average of Elements: " + average);

    }

}



//5. Reverse an Array


public class ReverseArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int[] reversed = new int[numbers.length];

        for (int i = 0; i < numbers.length; i++) {

            reversed[i] = numbers[numbers.length - 1 - i];

        }

        System.out.print("Reversed Array: ");

        for (int number : reversed) {

            System.out.print(number + " ");

        }

    }

}


//6. Check if an Array Contains a Specific Element


public class ElementSearch {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int target = 7;

        boolean found = false;

        for (int number : numbers) {

            if (number == target) {

                found = true;

                break;

            }

        }

        System.out.println("Element " + target + " found: " + found);

    }

}



//7. Count the Occurrences of a Specific Element


public class ElementCount {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 2, 9, 2};

        int target = 2;

        int count = 0;

        for (int number : numbers) {

            if (number == target) {

                count++;

            }

        }

        System.out.println("Element " + target + " occurs " + count + " times.");

    }

}



//8. Remove Duplicates from an Array


import java.util.Arrays;


public class RemoveDuplicates {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 2, 9, 4};

        int n = numbers.length;

        Arrays.sort(numbers);

        int[] result = new int[n];

        int j = 0;

        for (int i = 0; i < n - 1; i++) {

            if (numbers[i] != numbers[i + 1]) {

                result[j++] = numbers[i];

            }

        }

        result[j++] = numbers[n - 1];

        System.out.print("Array without duplicates: ");

        for (int i = 0; i < j; i++) {

            System.out.print(result[i] + " ");

        }

    }

}


//9. Find the Index of a Specific Element


public class FindIndex {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int target = 7;

        int index = -1;

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == target) {

                index = i;

                break;

            }

        }

        System.out.println("Index of " + target + ": " + index);

    }

}


//10. Print Array Elements in a Single Line


public class PrintArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        System.out.print("Array elements: ");

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}



//11. Copy an Array


import java.util.Arrays;


public class CopyArray {

    public static void main(String[] args) {

        int[] original = {4, 2, 7, 1, 9};

        int[] copy = Arrays.copyOf(original, original.length);

        System.out.print("Copied Array: ");

        for (int number : copy) {

            System.out.print(number + " ");

        }

    }

}


//12. Sort an Array in Ascending Order


import java.util.Arrays;


public class SortArray {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        Arrays.sort(numbers);

        System.out.print("Sorted Array: ");

        for (int number : numbers) {

            System.out.print(number + " ");

        }

    }

}



//13. Find the Sum of Even Numbers in an Array


public class SumEvenNumbers {

    public static void main(String[] args) {

        int[] numbers = {4, 2, 7, 1, 9};

        int sum = 0;

        for (int number : numbers) {

            if (number % 2 == 0) {

                sum += number;

            }

        }

        System.out.println("Sum of Even Numbers: " + sum);

    }

}



/////////////////////  TWO DIMENSIONAL ARRAYS - SOLUTIONS ////////////////


//1. Print a Two-Dimensional Array


public class Print2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        System.out.println("Two-Dimensional Array:");

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                System.out.print(array[i][j] + " ");

            }

            System.out.println();

        }

    }

}


//2. Find the Sum of All Elements in a Two-Dimensional Array


public class Sum2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        int sum = 0;

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                sum += array[i][j];

            }

        }

        System.out.println("Sum of All Elements: " + sum);

    }

}


//3. Find the Maximum Element in a Two-Dimensional Array


public class MaxElement2DArray {

    public static void main(String[] args) {

        int[][] array = {

            {1, 2, 3},

            {4, 5, 6},

            {7, 8, 9}

        };


        int max = array[0][0];

        for (int i = 0; i < array.length; i++) {

            for (int j = 0; j < array[i].length; j++) {

                if (array[i][j] > max) {

                    max = array[i][j];

                }

            }

        }

        System.out.println("Maximum Element: " + max);

    }

}


 Object type array


public class ObjectTypeArray {


public static void main(String[] args) {

Object[] a = new Object[5];

      

        a[0] = "Hello";      // String

        a[1] = 123;          // Integer

        a[2] = 45.67;        // Double

        a[3] = true;         // Boolean

        a[4] = 'A';          // Character


       //access specific value from array

       System.out.println(a[2]); //45.67

       System.out.println(a[2].getClass().getSimpleName()); //Double type of object

              

       System.out.println("Reading data from the array using for loop:");

        for (int i = 0; i < a.length; i++) {

             System.out.println(a[i]);

        }

System.out.println("Reading data from the Object array using for-each loop:");

        for (Object element : a) {

           System.out.println(element);

        }

}

}


Sorting array


import java.util.Arrays;

import java.util.Collections;


public class SortArray {

    public static void main(String[] args) {

        

    //Sorting numbers  - ascending order

    int numbers[] = {4, 2, 7, 1, 9};

        

    System.out.println("Before sorting:"+ Arrays.toString(numbers)); //printing array without loop

        Arrays.sort(numbers);

        System.out.println("After sorting:" +Arrays.toString(numbers));

        

        

        //Sorting strings - - ascending order

        String names[]= {"Smith","John","David","Scott"};

        System.out.println("Before sorting:"+ Arrays.toString(names)); 

        Arrays.sort(names);

        System.out.println("After sorting:" +Arrays.toString(names));

        

        

        //Sorting numbers or strings - descending order

        Integer ids[]= {100,500,200,400,600,300};

        

        System.out.println("Before sorting:" +Arrays.toString(ids));

        Arrays.sort(ids, Collections.reverseOrder());

        System.out.println("After sorting in Ascending order:"+ Arrays.toString(ids));

    }

}


Searching element in an array


import java.util.Arrays;


public class SearchElementinArray {


public static void main(String[] args) {

//Linear Search (Works on Unsorted Arrays)

int[] numbers = {5, 3, 8, 1, 2};

        int searchElement = 8;

        boolean found = false;

        

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == searchElement) {

                found = true;

                System.out.println("Element " + searchElement + " found at index " + i);

                break;

            }

        }

        

        if (found==false) {

            System.out.println("Element " + searchElement + " not found in the array.");

        }

        

      //Binary Search (Works on Sorted Arrays)

//If the array is unsorted, you should sort it using Arrays.sort() before performing a binary search.

int[] numbers = {1, 2, 3, 5, 8};  // Array must be sorted

     int searchElement = 3;

        

     int index = Arrays.binarySearch(numbers, searchElement); //method returns the index of the target element if found. If not found, it returns a negative value.

        

      if (index >= 0) {

            System.out.println("Element " + searchElement + " found at index " + index);

        } else {

            System.out.println("Element " + searchElement + " not found in the array.");

        }


}


}



Copying an array


import java.util.Arrays;


public class CopyArrayExample {

    public static void main(String[] args) {

        

        // Original array

        int originalArray[] = {1, 2, 3, 4, 5};

        

        // Method 1: Using a loop

        int copiedArray[] = new int[originalArray.length];

        for (int i = 0; i < originalArray.length; i++) {

            copiedArray[i] = originalArray[i];

        }

       

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        

        

        // Method 2: Using Arrays.copyOf()

        /*int copiedArray[] = Arrays.copyOf(originalArray, originalArray.length);

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

        

        // Method 3: Using System.arraycopy()

        /*int copiedArray[] = new int[originalArray.length];

        System.arraycopy(originalArray, 0, copiedArray, 0, originalArray.length);

        

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

        

        // Method 4: Using clone()

        /*int copiedArray[] = originalArray.clone();

        

        System.out.println("Original Array: " + Arrays.toString(originalArray));

        System.out.println("Copied Array" + Arrays.toString(copiedArray));

        */

    }

}


Equality of arrays



import java.util.Arrays;


public class ArrayEqualityExample {

    public static void main(String[] args) {

        

        int[] array1 = {1, 2, 3, 4, 5};

        int[] array2 = {1, 2, 3, 4, 5};

        //int[] array2 = {5, 4, 3, 2, 1};

        

        // Method 1: Using Arrays.equals()

        //boolean result = Arrays.equals(array1, array2);

        //System.out.println("Are array1 and array2 equal ? " + result);

        

        

        // Method 2: Using a loop 

        boolean result = true;

   

        if (array1.length != array2.length) 

        {

        result = false;

        } 

        else 

        {

        for (int i = 0; i < array1.length; i++) 

        {

                if (array1[i] != array2[i]) 

                {

                    result = false;

                    break;

                }

            }

        }

        

        System.out.println("Are array1 and array2 equal? " + result);

    }

}





Java Looping & Jumping Statements - Practice Programs with Solutions

 ////////////////////////////////////////////////////////////////////////////

// While loop

////////////////////////////////////////////////////////////////////////////


//Program1: Print Numbers from 1 to 10


public class PrintNumbers {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 10) {

            System.out.println(i);

            i++;

        }

    }

}


//Program2: Sum of First 10 Natural Numbers


public class SumNaturalNumbers {

    public static void main(String[] args) {

        int i = 1, sum = 0;

        while (i <= 10) {

            sum += i;

            i++;

        }

        System.out.println("Sum: " + sum);

    }

}


//Program 3: Factorial of a Number


public class Factorial {

    public static void main(String[] args) {

        int number = 5; // Example number

        int factorial = 1;

        int i = 1;

        while (i <= number) {

            factorial *= i;

            i++;

        }

        System.out.println("Factorial of " + number + " is: " + factorial);

    }

}


//Program1 4: Reverse a Number


public class ReverseNumber {

    public static void main(String[] args) {

        int number = 12345; // Example number

        int reverse = 0;

        while (number != 0) {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number /= 10;

        }

        System.out.println("Reversed Number: " + reverse);

    }

}


//Program 5: Count the Digits in a Number


public class CountDigits {

    public static void main(String[] args) {

        int number = 12345; // Example number

        int count = 0;

        while (number != 0) {

            number /= 10;

            count++;

        }

        System.out.println("Number of digits: " + count);

    }

}


//Program: 6 Check if a Number is Prime


public class PrimeCheck {

    public static void main(String[] args) {

        int number = 29; // Example number

        boolean isPrime = true;

        int i = 2;

        while (i <= number / 2) {

            if (number % i == 0) {

                isPrime = false;

                break;

            }

            i++;

        }

        if (isPrime) {

            System.out.println(number + " is a prime number.");

        } else {

            System.out.println(number + " is not a prime number.");

        }

    }

}



////Program: 7 Print Even Numbers Between 1 and 20


public class EvenNumbers {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 20) {

            if (i % 2 == 0) {

                System.out.println(i);

            }

            i++;

        }

    }

}


//Program 8. Sum of Digits in a Number


public class SumOfDigits {

    public static void main(String[] args) {

        int number = 12345; // Example number

        int sum = 0;

        while (number != 0) {

            int digit = number % 10;

            sum += digit;

            number /= 10;

        }

        System.out.println("Sum of digits: " + sum);

    }

}


//Program: 9. Find the Largest Digit in a Number


public class LargestDigit {

    public static void main(String[] args) {

        int number = 52679; // Example number

        int largest = 0;

        while (number != 0) {

            int digit = number % 10;

            if (digit > largest) {

                largest = digit;

            }

            number /= 10;

        }

        System.out.println("Largest digit: " + largest);

    }

}


//Program 10. Generate Fibonacci Series


public class FibonacciSeries {

    public static void main(String[] args) {

        int n1 = 0, n2 = 1, n3, i = 2, count = 10;

        System.out.print(n1 + " " + n2);

        while (i < count) {

            n3 = n1 + n2;

            System.out.print(" " + n3);

            n1 = n2;

            n2 = n3;

            i++;

        }

    }

}

//Program 11. Check if a Number is Palindrome


public class PalindromeCheck {

    public static void main(String[] args) {

        int number = 121; // Example number

        int originalNumber = number;

        int reverse = 0;

        while (number != 0) {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number /= 10;

        }

        if (originalNumber == reverse) {

            System.out.println(originalNumber + " is a palindrome.");

        } else {

            System.out.println(originalNumber + " is not a palindrome.");

        }

    }

}



//Program 12. Sum of Even Numbers from 1 to N


public class SumEvenNumbers {

    public static void main(String[] args) {

        int n = 10; // Example value of N

        int sum = 0;

        int i = 1;

        while (i <= n) {

            if (i % 2 == 0) {

                sum += i;

            }

            i++;

        }

        System.out.println("Sum of even numbers from 1 to " + n + " is: " + sum);

    }

}


//Program13. Sum of Odd Numbers from 1 to N


public class SumOddNumbers {

    public static void main(String[] args) {

        int n = 10; // Example value of N

        int sum = 0;

        int i = 1;

        while (i <= n) {

            if (i % 2 != 0) {

                sum += i;

            }

            i++;

        }

        System.out.println("Sum of odd numbers from 1 to " + n + " is: " + sum);

    }

}



////////////////////////////////////////////////////////////////////////////

// do-while loop

////////////////////////////////////////////////////////////////////////////


// Program 1. Print Numbers from 1 to 10


public class PrintNumbers {

    public static void main(String[] args) {

        int i = 1;

        do {

            System.out.println(i);

            i++;

        } while (i <= 10);

    }

}


// Program 2. Sum of Digits in a Number


public class SumOfDigits {

    public static void main(String[] args) {

        int number = 12345; // Example number

        int sum = 0;

        do {

            int digit = number % 10;

            sum += digit;

            number /= 10;

        } while (number != 0);

        System.out.println("Sum of digits: " + sum);

    }

}


// Program 3. Reverse a Number


public class ReverseNumber {

    public static void main(String[] args) {

        int number = 12345; // Example number

        int reverse = 0;

        do {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number /= 10;

        } while (number != 0);

        System.out.println("Reversed Number: " + reverse);

    }

}


// Program 4. Check if a Number is Palindrome


public class PalindromeCheck {

    public static void main(String[] args) {

        int number = 121; // Example number

        int originalNumber = number;

        int reverse = 0;

        do {

            int digit = number % 10;

            reverse = reverse * 10 + digit;

            number /= 10;

        } while (number != 0);

        if (originalNumber == reverse) {

            System.out.println(originalNumber + " is a palindrome.");

        } else {

            System.out.println(originalNumber + " is not a palindrome.");

        }

    }

}


// Program 5. Menu-Driven Program for Basic Arithmetic Operations


import java.util.Scanner;

public class ArithmeticOperations {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int choice;

        do {

            System.out.println("Menu:");

            System.out.println("1. Addition");

            System.out.println("2. Subtraction");

            System.out.println("3. Multiplication");

            System.out.println("4. Division");

            System.out.println("5. Exit");

            System.out.print("Enter your choice: ");

            choice = scanner.nextInt();


            if (choice >= 1 && choice <= 4) {

                System.out.print("Enter first number: ");

                double num1 = scanner.nextDouble();

                System.out.print("Enter second number: ");

                double num2 = scanner.nextDouble();


                switch (choice) {

                    case 1:

                        System.out.println("Result: " + (num1 + num2));

                        break;

                    case 2:

                        System.out.println("Result: " + (num1 - num2));

                        break;

                    case 3:

                        System.out.println("Result: " + (num1 * num2));

                        break;

                    case 4:

                        if (num2 != 0) {

                            System.out.println("Result: " + (num1 / num2));

                        } else {

                            System.out.println("Division by zero is not allowed.");

                        }

                        break;

                }

            } else if (choice != 5) {

                System.out.println("Invalid choice! Please select a valid option.");

            }

        } while (choice != 5);

        scanner.close();

        System.out.println("Program terminated.");

    }

}


////////////////////////////////////////////////////////////////////////////

// for loop

////////////////////////////////////////////////////////////////////////////



// Program 1. Print Numbers 1 to 10


public class PrintNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {

            System.out.println(i);

        }

    }

}


// Program 2. Print Even Numbers from 1 to 20


public class PrintEvenNumbers {

    public static void main(String[] args) {

        for (int i = 2; i <= 20; i += 2) {

            System.out.println(i);

        }

    }

}


// Program 3. Print Odd Numbers from 1 to 20


public class PrintOddNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 20; i += 2) {

            System.out.println(i);

        }

    }

}


// Program 4. Print Multiples of 5 from 5 to 50


public class MultiplesOfFive {

    public static void main(String[] args) {

        for (int i = 5; i <= 50; i += 5) {

            System.out.println(i);

        }

    }

}



// Program 5. Calculate Sum of Numbers from 1 to 10


public class SumOfNumbers {

    public static void main(String[] args) {

        int sum = 0;

        for (int i = 1; i <= 10; i++) {

            sum += i;

        }

        System.out.println("Sum: " + sum);

    }

}


// Program 6. Print Squares of Numbers from 1 to 5


public class SquaresOfNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 5; i++) {

            System.out.println("Square of " + i + " is " + (i * i));

        }

    }

}



// Program 7. Print Cube of Numbers from 1 to 5


public class CubesOfNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 5; i++) {

            System.out.println("Cube of " + i + " is " + (i * i * i));

        }

    }

}



// Program 8. Print Numbers in Reverse Order from 10 to 1


public class ReverseOrder {

    public static void main(String[] args) {

        for (int i = 10; i >= 1; i--) {

            System.out.println(i);

        }

    }

}


// Program 9. Print Prime Numbers between 1 and 50


public class PrimeNumbers {

    public static void main(String[] args) {

        for (int num = 2; num <= 50; num++) {

            boolean isPrime = true;

            for (int i = 2; i <= num / 2; i++) {

                if (num % i == 0) {

                    isPrime = false;

                    break;

                }

            }

            if (isPrime) {

                System.out.println(num);

            }

        }

    }

}


// Program 10. Print Sum of Even Numbers between 1 and 20


public class SumEvenNumbers {

    public static void main(String[] args) {

        int sum = 0;

        for (int i = 2; i <= 20; i += 2) {

            sum += i;

        }

        System.out.println("Sum of even numbers: " + sum);

    }

}



// Program 11. Print Sum of Odd Numbers between 1 and 20


public class SumOddNumbers {

    public static void main(String[] args) {

        int sum = 0;

        for (int i = 1; i <= 20; i += 2) {

            sum += i;

        }

        System.out.println("Sum of odd numbers: " + sum);

    }

}


// Program 12. Print Table of 7


public class MultiplicationTable {

    public static void main(String[] args) {

        int number = 7;

        for (int i = 1; i <= 10; i++) {

            System.out.println(number + " x " + i + " = " + (number * i));

        }

    }

}


// Program 13. Print Numbers Divisible by 3 and 5 from 1 to 100


public class DivisibleByThreeAndFive {

    public static void main(String[] args) {

        for (int i = 1; i <= 100; i++) {

            if (i % 3 == 0 && i % 5 == 0) {

                System.out.println(i);

            }

        }

    }

}


// Program 14. Count Number of Digits in a Number


public class CountDigits {

    public static void main(String[] args) {

        int number = 12345;

        int count = 0;

        for (int temp = number; temp > 0; temp /= 10) {

            count++;

        }

        System.out.println("Number of digits: " + count);

    }

}


// Program 15. Print Multiples of 7 between 1 and 100


public class MultiplesOfSeven {

    public static void main(String[] args) {

        for (int i = 7; i <= 100; i += 7) {

            System.out.println(i);

        }

    }

}


////////////////////////////////////////////////////////////////////////////

// continue

////////////////////////////////////////////////////////////////////////////


//Program 1. Print Odd Numbers


public class PrintOddNumbers {

    public static void main(String[] args) {

        for (int i = 1; i <= 20; i++) {

            if (i % 2 == 0) {

                continue; // Skip even numbers

            }

            System.out.println(i);

        }

    }

}

//Program 2. Skip Multiples of 5


public class SkipMultiplesOfFive {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 30) {

            if (i % 5 == 0) {

                i++; // Increment the counter before continue to avoid infinite loop

                continue; // Skip multiples of 5

            }

            System.out.println(i);

            i++;

        }

    }

}



//Program 3. Skip Numbers Divisible by 3 and 4


public class SkipDivisibleByThreeAndFour {

    public static void main(String[] args) {

        for (int i = 1; i <= 50; i++) {

            if (i % 3 == 0 && i % 4 == 0) {

                continue; // Skip numbers divisible by both 3 and 4

            }

            System.out.println(i);

        }

    }

}




////////////////////////////////////////////////////////////////////////////

// break

////////////////////////////////////////////////////////////////////////////



//Program 1. Find First Even Number


public class FindFirstEvenNumber {

    public static void main(String[] args) {

        for (int i = 1; i <= 20; i++) {

            if (i % 2 == 0) {

                System.out.println("First even number: " + i);

                break; // Exit the loop after finding the first even number

            }

        }

    }

}


//Program 2: Stop at First Multiple of 7


public class StopAtFirstMultipleOfSeven {

    public static void main(String[] args) {

        int i = 1;

        while (i <= 50) {

            if (i % 7 == 0) {

                System.out.println("First multiple of 7: " + i);

                break; // Exit the loop after finding the first multiple of 7

            }

            i++;

        }

    }

}


//Program 3. Find Number Greater Than 15


public class FindNumberGreaterThanFifteen {

    public static void main(String[] args) {

        for (int i = 1; i <= 30; i++) {

            if (i > 15) {

                System.out.println("Number greater than 15: " + i);

                break; // Exit the loop after finding a number greater than 15

            }

        }

    }

}


Java Conditional Statements - Practice Programs with Solutions

 //// 1) if Statement Programs


//Program 1: Check if a number is positive


public class PositiveCheck {

    public static void main(String[] args) {

        int num = 5;

        if (num > 0) {

            System.out.println(num + " is positive.");

        }

    }

}



//Program 2: Check if a person is eligible to vote (age >= 18)


public class VotingEligibility {

    public static void main(String[] args) {

        int age = 20;

        if (age >= 18) {

            System.out.println("You are eligible to vote.");

        }

    }

}



//Program 3: Check if a year is a leap year


public class LeapYearCheck {

    public static void main(String[] args) {

        int year = 2020;

        if (year % 4 == 0) {

            System.out.println(year + " is a leap year.");

        }

    }

}


//Program 4: Check if a character is uppercase


public class UpperCaseCheck {

    public static void main(String[] args) {

        char ch = 'A';

        if (ch >= 'A' && ch <= 'Z') {

            System.out.println(ch + " is an uppercase letter.");

        }

    }

}


//Program 5: Check if a number is a multiple of 10


public class MultipleOfTen {

    public static void main(String[] args) {

        int num = 30;

        if (num % 10 == 0) {

            System.out.println(num + " is a multiple of 10.");

        }

    }

}



//// 2) if..else Statement Programs



//Program 1: Check if a number is even or odd


public class EvenOddCheck {

    public static void main(String[] args) {

        int num = 7;

        if (num % 2 == 0) {

            System.out.println(num + " is even.");

        } else {

            System.out.println(num + " is odd.");

        }

    }

}


//Program 2: Check if a person is a teenager (age between 13 and 19)


public class TeenagerCheck {

    public static void main(String[] args) {

        int age = 16;

        if (age >= 13 && age <= 19) {

            System.out.println("You are a teenager.");

        } else {

            System.out.println("You are not a teenager.");

        }

    }

}


//Program 3: Compare two numbers and print the larger one


public class LargerNumber {

    public static void main(String[] args) {

        int a = 5, b = 10;

        if (a > b) {

            System.out.println(a + " is larger.");

        } else {

            System.out.println(b + " is larger.");

        }

    }

}


//Program 4: Check if a number is positive, negative, or zero


public class NumberCheck {

    public static void main(String[] args) {

        int num = -3;

        if (num > 0) {

            System.out.println(num + " is positive.");

        } else if (num < 0) {

            System.out.println(num + " is negative.");

        } else {

            System.out.println(num + " is zero.");

        }

    }

}


//Program 5: Check if a person is eligible for a senior citizen discount (age >= 60)


public class SeniorDiscount {

    public static void main(String[] args) {

        int age = 65;

        if (age >= 60) {

            System.out.println("You are eligible for a senior citizen discount.");

        } else {

            System.out.println("You are not eligible for a senior citizen discount.");

        }

    }

}



//// 3) Nested if Statement Programs


//Program 1: Check if a number is positive and even


public class PositiveEvenCheck {

    public static void main(String[] args) {

        int num = 8;

        if (num > 0) {

            if (num % 2 == 0) {

                System.out.println(num + " is positive and even.");

            }

        }

    }

}


//Program 2: Check if a character is an uppercase vowel


public class UppercaseVowelCheck {

    public static void main(String[] args) {

        char ch = 'A';

        if (ch >= 'A' && ch <= 'Z') {

            if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

                System.out.println(ch + " is an uppercase vowel.");

            }

        }

    }

}


//Program 3: Find the largest of three numbers


public class LargestOfThree {

    public static void main(String[] args) {

        int a = 5, b = 8, c = 3;


        if (a > b && a > c) {

            System.out.println(a + " is the largest.");

        } else if (b > c) {

            System.out.println(b + " is the largest.");

        } else {

            System.out.println(c + " is the largest.");

        }

    }

}



//Program 4: Check if a number is a multiple of both 5 and 10


public class MultipleOfFiveAndTen {

    public static void main(String[] args) {

        int num = 50;

        if (num % 5 == 0) {

            if (num % 10 == 0) {

                System.out.println(num + " is a multiple of both 5 and 10.");

            }

        }

    }

}


//Program 5: Determine the grade of a student based on their score


public class StudentGrade {

    public static void main(String[] args) {

        int score = 85;

        

        if (score >= 90) {

            System.out.println("Grade A");

        } else {

            if (score >= 80) {

                System.out.println("Grade B");

            } else {

                if (score >= 70) {

                    System.out.println("Grade C");

                } else {

                    if (score >= 60) {

                        System.out.println("Grade D");

                    } else {

                        System.out.println("Grade F");

                    }

                }

            }

        }

    }

}



//Program 6 Check if a character is a vowel or consonant

public class VowelConsonantCheck {

    public static void main(String[] args) {

        char ch = 'E';

        

        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {

            System.out.println(ch + " is a vowel.");

        } else {

            if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

                System.out.println(ch + " is a vowel.");

            } else {

                System.out.println(ch + " is a consonant.");

            }

        }

    }

}



//Program 7: Check if a number is divisible by both 2 and 3


public class DivisibilityCheck {

    public static void main(String[] args) {

        int num = 12;

        

        if (num % 2 == 0) {

            if (num % 3 == 0) {

                System.out.println(num + " is divisible by both 2 and 3.");

            } else {

                System.out.println(num + " is divisible by 2 but not by 3.");

            }

        } else {

            if (num % 3 == 0) {

                System.out.println(num + " is divisible by 3 but not by 2.");

            } else {

                System.out.println(num + " is not divisible by either 2 or 3.");

            }

        }

    }

}



//// 4) switch Statement Programs



//Program 1: Print the day of the week based on an integer input


public class DayOfWeek {

    public static void main(String[] args) {

        int day = 3;

        switch (day) {

            case 1:

                System.out.println("Monday");

                break;

            case 2:

                System.out.println("Tuesday");

                break;

            case 3:

                System.out.println("Wednesday");

                break;

            case 4:

                System.out.println("Thursday");

                break;

            case 5:

                System.out.println("Friday");

                break;

            case 6:

                System.out.println("Saturday");

                break;

            case 7:

                System.out.println("Sunday");

                break;

            default:

                System.out.println("Invalid day");

        }

    }

}


//Program 2: Print the corresponding month name for a given month number


public class MonthName {

    public static void main(String[] args) {

        int month = 5;

        switch (month) {

            case 1:

                System.out.println("January");

                break;

            case 2:

                System.out.println("February");

                break;

            case 3:

                System.out.println("March");

                break;

            case 4:

                System.out.println("April");

                break;

            case 5:

                System.out.println("May");

                break;

            case 6:

                System.out.println("June");

                break;

            case 7:

                System.out.println("July");

                break;

            case 8:

                System.out.println("August");

                break;

            case 9:

                System.out.println("September");

                break;

            case 10:

                System.out.println("October");

                break;

            case 11:

                System.out.println("November");

                break;

            case 12:

                System.out.println("December");

                break;

            default:

                System.out.println("Invalid month");

        }

    }

}


// Program 3: Display a grade based on a given score


public class GradeCalculator {

    public static void main(String[] args) {

        int score = 85;

        switch (score / 10) {

            case 10:

            case 9:

                System.out.println("Grade A");

                break;

            case 8:

                System.out.println("Grade B");

                break;

            case 7:

                System.out.println("Grade C");

                break;

            case 6:

                System.out.println("Grade D");

                break;

            default:

                System.out.println("Grade F");

        }

    }

}


//Program 4: Perform basic arithmetic operations based on user input


public class ArithmeticOperations {

    public static void main(String[] args) {

        char operator = '+';

        int a = 10, b = 5;

        switch (operator) {

            case '+':

                System.out.println("Result: " + (a + b));

                break;

            case '-':

                System.out.println("Result: " + (a - b));

                break;

            case '*':

                System.out.println("Result: " + (a * b));

                break;

            case '/':

                System.out.println("Result: " + (a / b));

                break;

            default:

                System.out.println("Invalid operator");

        }

    }

}


//Program 5: Print the season based on the month number



public class SeasonCheck {

    public static void main(String[] args) {

        int month = 4;

        switch (month) {

            case 12:

            case 1:

            case 2:

                System.out.println("Winter");

                break;

            case 3:

            case 4:

            case 5:

                System.out.println("Spring");

                break;

            case 6:

            case 7:

            case 8:

                System.out.println("Summer");

                break;

            case 9:

            case 10:

            case 11:

                System.out.println("Autumn");

                break;

            default:

                System.out.println("Invalid month");

        }

    }

}


Java Operators - Practice Programs with Solutions

 //Exercise 1: Arithmetic Operations


public class ArithmeticOperations {

    public static void main(String[] args) {

        int a = 20;

        int b = 5;


        int sum = a + b;

        int difference = a - b;

        int product = a * b;

        int quotient = a / b;

        int remainder = a % b;


        System.out.println("Sum: " + sum);

        System.out.println("Difference: " + difference);

        System.out.println("Product: " + product);

        System.out.println("Quotient: " + quotient);

        System.out.println("Remainder: " + remainder);

    }

}



//Exercise 2: Swapping Values


public class SwapValues {

    public static void main(String[] args) {

        int x = 10;

        int y = 20;


        // Swapping using arithmetic operators

        x = x + y;

        y = x - y;

        x = x - y;


        System.out.println("After swapping:");

        System.out.println("x = " + x);

        System.out.println("y = " + y);

    }

}


//Exercise 3: Area and Perimeter of a Rectangle


public class Rectangle {

    public static void main(String[] args) {

        double length = 15.5;

        double width = 10.0;


        double area = length * width;

        double perimeter = 2 * (length + width);


        System.out.println("Area: " + area);

        System.out.println("Perimeter: " + perimeter);

    }

}



//Exercise 4: Convert Celsius to Fahrenheit


public class TemperatureConversion {

    public static void main(String[] args) {

        double celsius = 25.0;


        double fahrenheit = (celsius * 9/5) + 32;


        System.out.println(celsius + " Celsius is equal to " + fahrenheit + " Fahrenheit.");

    }

}


//Exercise 5: Simple Interest Calculation


public class SimpleInterest {

    public static void main(String[] args) {

        double principal = 10000;

        double rate = 5; // Interest rate per year in percentage

        double time = 3; // Time in years


        double simpleInterest = (principal * rate * time) / 100;


        System.out.println("Simple Interest: " + simpleInterest);

    }

}


//Exercise 6: Calculate the Average

public class AverageCalculator {

    public static void main(String[] args) {

        double num1 = 8.5;

        double num2 = 6.7;

        double num3 = 9.2;


        double average = (num1 + num2 + num3) / 3;


        System.out.println("Average: " + average);

    }

}




Followers