public class ReverseString {
public static void main(String[] args) {
String str = "Hello, World!";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed String: " + reversed);
}
}
Explanation: The StringBuilder class has a reverse()
method, which reverses the string. We convert the StringBuilder back to a String using toString()
.
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = isPalindrome(str);
System.out.println("Is the string a palindrome? " + isPalindrome);
}
public static boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
}
Explanation: The string is reversed and compared with the original string. If both are the same, it's a palindrome.
public class LargestElement {
public static void main(String[] args) {
int[] arr = {4, 7, 2, 9, 1};
int largest = findLargest(arr);
System.out.println("The largest element is: " + largest);
}
public static int findLargest(int[] arr) {
int largest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
}
Explanation: The program iterates through the array and keeps track of the largest element found so far.
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // The number of terms in the Fibonacci sequence
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
Explanation: The Fibonacci series is generated using a recursive function. The base cases are fibonacci(0) = 0
and fibonacci(1) = 1
.
public class Factorial {
public static void main(String[] args) {
int num = 5; // Example number
int result = factorial(num);
System.out.println("Factorial of " + num + " is: " + result);
}
public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
}
Explanation: The factorial of a number n
is calculated recursively. The base case is when n
is 0, returning 1.
public class PrimeNumber {
public static void main(String[] args) {
int num = 29; // Example number
boolean isPrime = isPrime(num);
System.out.println(num + " is prime: " + isPrime);
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Explanation: The program checks for factors of the number up to the square root of the number for efficiency. If the number is divisible by any of these factors, it's not prime.
public class CountCharacter {
public static void main(String[] args) {
String str = "programming";
char target = 'g';
int count = countOccurrences(str, target);
System.out.println("Character '" + target + "' occurs " + count + " times.");
}
public static int countOccurrences(String str, char target) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == target) {
count++;
}
}
return count;
}
}
Explanation: The program iterates through each character in the string and counts how many times the target character appears.
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {4, 7, 2, 9, 1};
int secondLargest = findSecondLargest(arr);
System.out.println("The second largest element is: " + secondLargest);
}
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
return secondLargest;
}
}
Explanation: The program tracks the largest and second largest elements by updating them during the iteration through the array.
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
int missingNumber = findMissingNumber(arr, 5); // N = 5
System.out.println("The missing number is: " + missingNumber);
}
public static int findMissingNumber(int[] arr, int n) {
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
return expectedSum - actualSum;
}
}
Explanation: The expected sum of numbers from 1 to N is calculated using the formula N * (N + 1) / 2
. The actual sum of the array is calculated, and the difference gives the missing number.
public class StringLength {
public static void main(String[] args) {
String str = "Hello, World!";
int length = findLength(str);
System.out.println("Length of the string is: " + length);
}
public static int findLength(String str) {
int length = 0;
try {
while (true) {
str.charAt(length);
length++;
}
} catch (StringIndexOutOfBoundsException e) {
return length;
}
}
}
Explanation: The program uses charAt()
to traverse through each character in the string, incrementing a counter until an exception is thrown, indicating the end of the string.
public class SumOfDigits {
public static void main(String[] args) {
int number = 12345;
int sum = sumOfDigits(number);
System.out.println("Sum of digits: " + sum);
}
public static int sumOfDigits(int number) {
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}
Explanation: The program calculates the sum of digits by using the modulus operator to get the last digit and then dividing the number by 10 to remove the last digit.
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 2, 3, 4, 4, 5};
int[] result = removeDuplicates(arr);
System.out.print("Array after removing duplicates: ");
for (int num : result) {
System.out.print(num + " ");
}
}
public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int num : arr) {
set.add(num);
}
int[] result = new int[set.size()];
int index = 0;
for (int num : set) {
result[index++] = num;
}
return result;
}
}
Explanation: We use a HashSet
to store unique elements since it automatically handles duplicate values.
import java.util.HashSet;
import java.util.Set;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {4, 5, 6, 7};
int[] intersection = findIntersection(arr1, arr2);
System.out.print("Intersection: ");
for (int num : intersection) {
System.out.print(num + " ");
}
}
public static int[] findIntersection(int[] arr1, int[] arr2) {
Set<Integer> set1 = new HashSet<>();
for (int num : arr1) {
set1.add(num);
}
Set<Integer> intersection = new HashSet<>();
for (int num : arr2) {
if (set1.contains(num)) {
intersection.add(num);
}
}
int[] result = new int[intersection.size()];
int index = 0;
for (int num : intersection) {
result[index++] = num;
}
return result;
}
}
Explanation: The program uses two sets: one to store elements of the first array and another to store the intersection of both arrays.
public class MissingNumberInSequence {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6};
int n = 6; // The sequence goes from 1 to 6
int missingNumber = findMissingNumber(arr, n);
System.out.println("The missing number is: " + missingNumber);
}
public static int findMissingNumber(int[] arr, int n) {
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
return expectedSum - actualSum;
}
}
Explanation: The expected sum of the first N numbers is calculated using the formula N * (N + 1) / 2
. By subtracting the sum of the array from the expected sum, the missing number is found.
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2; // Rotate by 2 positions
rotate(arr, k);
System.out.print("Array after rotation: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void rotate(int[] arr, int k) {
int n = arr.length;
k = k % n; // In case k is larger than n
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
private static void reverse(int[] arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Explanation: The array is rotated by reversing parts of the array. First, the whole array is reversed, then the first k
elements are reversed, followed by the rest.
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = merge(arr1, arr2);
System.out.println("Merged array: " + Arrays.toString(merged));
}
public static int[] merge(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < arr1.length) {
merged[k++] = arr1[i++];
}
while (j < arr2.length) {
merged[k++] = arr2[j++];
}
return merged;
}
}
Explanation: This program merges two sorted arrays by comparing the elements of both arrays and inserting the smaller element into the merged array.
import java.util.ArrayList;
import java.util.List;
public class CommonElements {
public static void main(String[] args) {
int[] arr1 = {1, 2, 4, 5, 6};
int[] arr2 = {2, 5, 6, 7};
List<Integer> common = findCommonElements(arr1, arr2);
System.out.println("Common elements: " + common);
}
public static List<Integer> findCommonElements(int[] arr1, int[] arr2) {
List<Integer> common = new ArrayList<>();
int i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] == arr2[j]) {
common.add(arr1[i]);
i++;
j++;
} else if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
return common;
}
}
Explanation: The program uses two pointers to traverse the two sorted arrays and find common elements. If elements match, they are added to the result list.
public class CountWords {
public static void main(String[] args) {
String str = "This is a simple test string.";
int wordCount = countWords(str);
System.out.println("Number of words: " + wordCount);
}
public static int countWords(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
String[] words = str.trim().split("\\s+");
return words.length;
}
}
Explanation: The program trims the string to remove leading and trailing spaces, then splits it based on one or more whitespace characters using a regular expression (\\s+
), and finally counts the number of elements in the resulting array.
import java.util.LinkedHashMap;
import java.util.Map;
public class FirstNonRepeatedCharacter {
public static void main(String[] args) {
String str = "swiss";
char result = findFirstNonRepeatedCharacter(str);
System.out.println("First non-repeated character: " + result);
}
public static char findFirstNonRepeatedCharacter(String str) {
Map<Character, Integer> charCountMap = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0'; // If no unique character found
}
}
Explanation: A LinkedHashMap
is used to keep the order of characters. The program counts occurrences of each character and returns the first character with a count of 1.
import java.util.Arrays;
public class KthLargestElement {
public static void main(String[] args) {
int[] arr = {7, 10, 4, 3, 20, 15};
int k = 3;
int kthLargest = findKthLargest(arr, k);
System.out.println("The " + k + "th largest element is: " + kthLargest);
}
public static int findKthLargest(int[] arr, int k) {
Arrays.sort(arr);
return arr[arr.length - k];
}
}
Explanation: The program sorts the array in ascending order and then returns the element at the arr.length - k
index, which corresponds to the Kth largest element.
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
String result = longestCommonPrefix(strs);
System.out.println("Longest common prefix: " + result);
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) {
return "";
}
}
}
return prefix;
}
}
Explanation: The program iterates through the list of strings, reducing the common prefix until it is found for all strings. The indexOf
method checks if the current prefix is a prefix of each string.
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean result = areAnagrams(str1, str2);
System.out.println("Are the strings anagrams? " + result);
}
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}
Explanation: The program first checks if the strings have the same length. It then sorts both strings and compares them for equality. If they are identical after sorting, they are anagrams.
public class MissingNumberInSortedArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5, 6};
int missingNumber = findMissingNumber(arr);
System.out.println("The missing number is: " + missingNumber);
}
public static int findMissingNumber(int[] arr) {
int n = arr.length + 1;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
return expectedSum - actualSum;
}
}
Explanation: This solution calculates the sum of the expected sequence (from 1 to n) and subtracts the sum of the array elements to find the missing number.
import java.util.HashSet;
import java.util.Set;
public class PairsWithSum {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
int targetSum = 7;
findPairs(arr, targetSum);
}
public static void findPairs(int[] arr, int targetSum) {
Set<Integer> seen = new HashSet<>();
for (int num : arr) {
int complement = targetSum - num;
if (seen.contains(complement)) {
System.out.println("Pair found: (" + complement + ", " + num + ")");
}
seen.add(num);
}
}
}
Explanation: The program uses a HashSet
to store elements that have been visited. For each element in the array, it checks if the complement (i.e., targetSum - num
) is already in the set.