January 29, 2024

Java Array: Largest, Smallest, Search, Sort, Find Duplicates


import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArrayHandler {
    public static void main(String[] args) {
        int[] numbers = {5, 3, 9, 1, 5, 7, 2, 1, 8, 4, 6, 1};
        System.out.println("Find largest and smallest in an array:");
        findLargestAndSmallest(numbers);
       System.out.println("\nSearch element in an array:");
        int target = 17;
        System.out.println("Is " + target + " present? " + searchElement(numbers, target));
        System.out.println("\nSort elements in an array:");
        sortArray(numbers);
        System.out.println("\nHow to find duplicates in an array or list:");
        findDuplicates(numbers);
    }
    // Find largest and smallest in an array
    public static void findLargestAndSmallest(int[] array) {
        Arrays.sort(array);
        int smallest = array[0];
        int largest = array[array.length - 1];
        System.out.println("Smallest: " + smallest);
        System.out.println("Largest: " + largest);
    }
    // Search element in an array
    public static boolean searchElement(int[] array, int target) {
        for (int num : array) {
            if (num == target) {
                return true;
            }
        }
        return false;
    }
    // Sort elements in an array
    public static void sortArray(int[] array) {
        Arrays.sort(array);
        System.out.println("Sorted Array: " + Arrays.toString(array));
    }
    // How to find duplicates in an array or list
    public static void findDuplicates(int[] array) {
    	// A Set is a collection that does not allow duplicate elements. 
    	Set uniqueSet = new HashSet<>();
        Set duplicates = new HashSet<>();

        for (int num : array) {
            // If the element's already present, uniqueSet.add(num) returns false, meaning that it's a duplicate.
        	if (!uniqueSet.add(num)) {
                duplicates.add(num);
            }
        }
        System.out.println("Duplicate elements: " + duplicates);
    }

}

Want 1 to 1 personalized Java training? Email me at isingh30@gmail.com please.

January 26, 2024

Java Problems Solutions: Check if a String is a Palindrome


public class CheckPalindrome {
    public static void main(String[] args) {
    	String inputString = "Was it a car or a cat I saw?";
        // Check if the input string is a palindrome.
        if (isPalindrome(inputString)) {
            System.out.println("The given string is a palindrome.");
        } else {
            System.out.println("The given string is not a palindrome.");
        }
    }
    // Function to check if a string is a palindrome
    public static boolean isPalindrome(String str) {
        // Remove spaces and convert to lower case for case-insensitive comparison.
    	str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int left = 0;
        int right = str.length() - 1;
        // Check characters from both ends towards the center
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false; // Characters do not match, so its not a palindrome.
            }
            left++;
            right--;
        }
        return true; // All characters matched, so its a palindrome.
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please.


January 23, 2024

Java Problems Solutions: Generate Fibonacci series


public class FibonacciGenerator {
   public static void main(String[] args) {
       int numberMembers = 10; // Set the limit for the Fibonacci series
       generateFibonacci(numberMembers); // Generate and print the Fibonacci series
   }

   // Function to generate Fibonacci series up to a given limit
   public static void generateFibonacci(int limit) {
       // Check if the limit is less than or equal to 0
       if (limit <= 1) {
           System.out.println("Please provide a valid number of members greater than 1.");
           return;
       }

       // Initialize the first two numbers in the series
       int num1 = 0, num2 = 1;

       // Print the first two numbers
       System.out.print("Fibonacci series up to " + limit + " members: " + num1 + ", " + num2);

       // Generate the Fibonacci series
       for (int i = 1; i < limit-1; i++) {
           int nextNum = num1 + num2;
           // Print the next number
           System.out.print(", " + nextNum);
           // Update num1 and num2 for the next iteration
           num1 = num2;
           num2 = nextNum;
       }
   }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

:


January 22, 2024

Java Problems Solutions: Reverse a String and Check if a string is a palindrome


import java.util.Scanner;

public class StringReverser {
    public static void main(String[] args) {
        // Get input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String inputString = scanner.nextLine();
        scanner.close();

        // Step 2: Reverse the string
        String reversedString = reverseString(inputString);

        // Step 3: Display the reversed string
        System.out.println("The reversed string is: " + reversedString);

        // Step 4: Compare strings
        compareStrings(inputString, reversedString);
    }

    // Function to reverse a string
    private static String reverseString(String original) {
        StringBuilder reversed = new StringBuilder();
        for (int i = original.length() - 1; i >= 0; i--) {
            reversed.append(original.charAt(i));
        }
        return reversed.toString();
    }

    // Function to compare two strings
    private static void compareStrings(String str1, String str2) {
        // 1st way: Using equals() method (exact equality)
        boolean isEqual1 = str1.equals(str2);
        System.out.println("Using equals() method: Strings are equal? " + isEqual1);

        // 2nd way: Using equalsIgnoreCase() method
        boolean isEqual2 = str1.equalsIgnoreCase(str2);
        System.out.println("Using equalsIgnoreCase() method: Strings are equal? " + isEqual2);

        // 3rd way: Using compareTo() method
        int comparisonResult = str1.compareTo(str2);
        System.out.println("Using compareTo() method: Comparison result: " + comparisonResult);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video

: