0% found this document useful (0 votes)
15 views46 pages

Java Questions For Cloudy Coders

The document presents a collection of Java programming problems along with their solutions, covering a variety of topics such as string manipulation, number theory, and data structures. Each problem is clearly stated, followed by a concise Java code solution. The problems range from reversing strings and checking for palindromes to calculating factorials and finding prime numbers.

Uploaded by

chelsigupta14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views46 pages

Java Questions For Cloudy Coders

The document presents a collection of Java programming problems along with their solutions, covering a variety of topics such as string manipulation, number theory, and data structures. Each problem is clearly stated, followed by a concise Java code solution. The problems range from reversing strings and checking for palindromes to calculating factorials and finding prime numbers.

Uploaded by

chelsigupta14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Java Real-Life Problem-Solving Questions with Solutions

(Cloudy Coders)

1. Reverse a String

Problem: Write a Java program to reverse a given string without using the built-in reverse() method.

Solution:

public class ReverseString {

public static void main(String[] args) {

String str = "Hello World";

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

System.out.println(reversed);

2. Check for Palindrome

Problem: Determine if a given string is a palindrome.

Solution:

public class PalindromeCheck {

public static boolean isPalindrome(String str) {

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

return str.equals(reversed);

3. Fibonacci Sequence

Problem: Generate the first N numbers of the Fibonacci sequence.

Solution:

public class FibonacciSequence {

public static void main(String[] args) {

int n = 10;

int a = 0, b = 1;

System.out.print(a + " " + b);


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

int c = a + b;

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

a = b;

b = c;

4. Factorial Calculation

Problem: Compute the factorial of a given number using recursion.

Solution:

public class Factorial {

public static int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n - 1);

5. Prime Number Check

Problem: Check if a given number is prime.

Solution:

public class PrimeCheck {

public static boolean isPrime(int n) {

if (n <= 1) return false;

for (int i = 2; i <= Math.sqrt(n); i++) {

if (n % i == 0) return false;

return true;

6. Swap Two Numbers Without Temp Variable

Problem: Swap two numbers without using a third variable.


Solution:

public class SwapNumbers {

public static void main(String[] args) {

int a = 5, b = 10;

a = a + b;

b = a - b;

a = a - b;

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

7. Remove Duplicates from Array

Problem: Remove duplicate elements from an array.

Solution:

import java.util.Arrays;

public class RemoveDuplicates {

public static int[] removeDuplicates(int[] arr) {

return Arrays.stream(arr).distinct().toArray();

8. Find Second Largest Number in Array

Problem: Find the second largest number in an array.

Solution:

public class SecondLargest {

public static int secondLargest(int[] arr) {

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int n : arr) {

if (n > first) {

second = first;

first = n;

} else if (n > second && n != first) {


second = n;

return second;

9. Merge Two Sorted Arrays

Problem: Merge two sorted arrays into a single sorted array.

Solution:

import java.util.Arrays;

public class MergeSortedArrays {

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;

}
10. Find Missing Number in Array

Problem: Find the missing number in an array of integers from 1 to N.

Solution:

public class MissingNumber {

public static int findMissing(int[] arr, int n) {

int sum = n * (n + 1) / 2;

for (int num : arr) {

sum -= num;

return sum;

11. Check Armstrong Number

Problem: Determine if a number is an Armstrong number.

Solution:

public class ArmstrongNumber {

public static boolean isArmstrong(int n) {

int sum = 0, temp = n, digits = String.valueOf(n).length();

while (temp != 0) {

int digit = temp % 10;

sum += Math.pow(digit, digits);

temp /= 10;

return sum == n;

12. Find GCD of Two Numbers

Problem: Compute the Greatest Common Divisor (GCD) of two numbers.

Solution:

public class GCD {

public static int gcd(int a, int b) {


if (b == 0) return a;

return gcd(b, a % b);

13. Check Anagram Strings

Problem: Check if two strings are anagrams.

Solution:

import java.util.Arrays;

public class AnagramCheck {

public static boolean areAnagrams(String str1, String str2) {

14. Count Vowels and Consonants

Problem: Count vowels and consonants in a string.

Solution:

public class VowelConsonantCount {

public static void count(String str) {

int vowels = 0, consonants = 0;

str = str.toLowerCase();

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

if (c >= 'a' && c <= 'z') {

if ("aeiou".indexOf(c) != -1) vowels++;

else consonants++;

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

15. Find Duplicate Characters in a String

Problem: Find characters that occur more than once in a string.


Solution:

import java.util.HashMap;

import java.util.Map;

public class DuplicateCharacters {

public static void findDuplicates(String str) {

Map<Character, Integer> countMap = new HashMap<>();

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

countMap.put(c, countMap.getOrDefault(c, 0) + 1);

countMap.forEach((k, v) -> {

if (v > 1) System.out.println(k + ": " + v);

});

16. Find Largest Element in an Array

Problem: Find the largest element in an array.

Solution:

public class LargestElement {

public static int findLargest(int[] arr) {

int max = arr[0];

for (int num : arr) {

if (num > max) max = num;

return max;

17. Count Words in a String

Problem: Count the number of words in a string.

Solution:

public class WordCount {


public static int countWords(String str) {

String[] words = str.trim().split("\\s+");

return words.length;

18. Print Pyramid Pattern

Problem: Print a pyramid pattern of stars.

Solution:

public class PyramidPattern {

public static void printPyramid(int n) {

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

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

System.out.print(" ");

for (int k = 1; k <= (2 * i - 1); k++) {

System.out.print("*");

System.out.println();

19. Find Common Elements in Two Arrays

Problem: Find common elements between two arrays.

Solution:

import java.util.HashSet;

import java.util.Set;

public class CommonElements {

public static Set<Integer> findCommon(int[] arr1, int[] arr2) {

Set<Integer> set1 = new HashSet<>();

Set<Integer> common = new HashSet<>();


for (int num : arr1) {

set1.add(num);

for (int num : arr2) {

if (set1.contains(num)) common.add(num);

return common;

20. Reverse an Integer

Problem: Reverse digits of an integer.

Solution:

public class ReverseInteger {

public static int reverse(int n) {

int rev = 0;

while (n != 0) {

rev = rev * 10 + n % 10;

n /= 10;

return rev;

21. Find Second Largest Number in Array

Problem: Find the second largest number in an array.

Solution:

public class SecondLargest {

public static int secondLargest(int[] arr) {

int largest = Integer.MIN_VALUE;

int second = Integer.MIN_VALUE;

for (int num : arr) {

if (num > largest) {


second = largest;

largest = num;

} else if (num > second && num < largest) {

second = num;

return second;

22. Check if String is Palindrome (Case-insensitive)

Problem: Check if a given string is palindrome ignoring case.

Solution:

public class PalindromeString {

public static boolean isPalindrome(String str) {

str = str.toLowerCase();

int i = 0, j = str.length() - 1;

while (i < j) {

if (str.charAt(i) != str.charAt(j)) return false;

i++;

j--;

return true;

23. Remove All White Spaces from a String

Problem: Remove all spaces from a given string.

Solution:

public class RemoveSpaces {

public static String removeSpaces(String str) {

return str.replaceAll("\\s", "");

}
}

24. Print Fibonacci Series up to N terms

Problem: Print Fibonacci series up to n terms.

Solution:

public class FibonacciSeries {

public static void printFibonacci(int n) {

int a = 0, b = 1;

System.out.print(a + " " + b);

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

int c = a + b;

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

a = b;

b = c;

System.out.println();

25. Sum of Digits of a Number

Problem: Find sum of all digits of a given number.

Solution:

public class SumOfDigits {

public static int sumDigits(int num) {

int sum = 0;

while (num != 0) {

sum += num % 10;

num /= 10;

return sum;

26. Find Missing Number in Array (1 to n)


Problem: Find the missing number in an array containing numbers from 1 to n.

Solution:

public class MissingNumber {

public static int findMissing(int[] arr, int n) {

int total = n * (n + 1) / 2;

for (int num : arr) {

total -= num;

return total;

27. Print Prime Numbers Between 1 and N

Problem: Print all prime numbers up to n.

Solution:

public class PrimeNumbers {

public static void printPrimes(int n) {

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

if (isPrime(i)) System.out.print(i + " ");

System.out.println();

private static boolean isPrime(int num) {

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) return false;

return true;

28. Reverse Array In-Place

Problem: Reverse the elements of an array without using extra space.


Solution:

public class ReverseArray {

public static void reverse(int[] arr) {

int start = 0, end = arr.length - 1;

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

29. Check Armstrong Number

Problem: Check if a number is an Armstrong number.

Solution:

public class ArmstrongNumber {

public static boolean isArmstrong(int num) {

int sum = 0, temp = num, digits = String.valueOf(num).length();

while (temp != 0) {

sum += Math.pow(temp % 10, digits);

temp /= 10;

return sum == num;

30. Find Factorial of a Number (Recursive)

Problem: Find the factorial of a given number using recursion.

Solution:

public class FactorialRecursion {

public static long factorial(int n) {


if (n <= 1) return 1;

return n * factorial(n - 1);

31. Find GCD of Two Numbers

Problem: Find the Greatest Common Divisor (GCD) of two numbers.

Solution:

public class GCD {

public static int gcd(int a, int b) {

if (b == 0) return a;

return gcd(b, a % b);

32. Find LCM of Two Numbers

Problem: Find the Least Common Multiple (LCM) of two numbers.

Solution:

public class LCM {

public static int lcm(int a, int b) {

return (a * b) / gcd(a, b);

private static int gcd(int a, int b) {

if (b == 0) return a;

return gcd(b, a % b);

33. Count Vowels and Consonants in String

Problem: Count the number of vowels and consonants in a string.

Solution:

public class VowelConsonantCounter {

public static void count(String str) {


int vowels = 0, consonants = 0;

str = str.toLowerCase();

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

if (Character.isLetter(ch)) {

if ("aeiou".indexOf(ch) != -1) vowels++;

else consonants++;

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

34. Count Words in a Sentence

Problem: Count the total number of words in a sentence.

Solution:

public class WordCount {

public static int countWords(String sentence) {

String[] words = sentence.trim().split("\\s+");

return words.length;

35. Sort Array in Ascending Order

Problem: Sort an array in ascending order.

Solution:

import java.util.Arrays;

public class SortArray {

public static void sortArray(int[] arr) {

Arrays.sort(arr);

36. Find Largest of Three Numbers


Problem: Find the largest number among three numbers.

Solution:

public class LargestOfThree {

public static int largest(int a, int b, int c) {

return Math.max(a, Math.max(b, c));

37. Convert Character to ASCII Value

Problem: Convert a character into its ASCII value.

Solution:

public class CharToASCII {

public static int getASCII(char ch) {

return (int) ch;

38. Find Sum of N Natural Numbers

Problem: Calculate sum of first n natural numbers.

Solution:

public class SumNaturalNumbers {

public static int sum(int n) {

return n * (n + 1) / 2;

39. Check if Year is a Leap Year

Problem: Check if a given year is leap year.

Solution:

public class LeapYear {

public static boolean isLeapYear(int year) {

return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);

}
40. Swap Two Strings Without Third Variable

Problem: Swap two strings without using a temporary variable.

Solution:

public class SwapStrings {

public static void swap(String a, String b) {

a = a + b;

b = a.substring(0, a.length() - b.length());

a = a.substring(b.length());

System.out.println("After swap: a = " + a + ", b = " + b);

41. Find Power of a Number

Problem: Calculate the power of a number.

Solution:

public class PowerCalculator {

public static double power(double base, int exponent) {

return Math.pow(base, exponent);

42. Reverse a Number

Problem: Reverse the digits of a number.

Solution:

public class ReverseNumber {

public static int reverse(int num) {

int rev = 0;

while (num != 0) {

rev = rev * 10 + num % 10;

num /= 10;

return rev;

}
}

43. Count Even and Odd Numbers in Array

Problem: Count the number of even and odd integers in an array.

Solution:

public class CountEvenOdd {

public static void count(int[] arr) {

int even = 0, odd = 0;

for (int num : arr) {

if (num % 2 == 0) even++;

else odd++;

System.out.println("Even: " + even + ", Odd: " + odd);

44. Check if a String is Palindrome (Case-Insensitive)

Problem: Check whether a string is a palindrome regardless of case.

Solution:

public class PalindromeStringCI {

public static boolean isPalindrome(String str) {

str = str.toLowerCase();

return str.equals(new StringBuilder(str).reverse().toString());

45. Print Multiplication Table of a Number

Problem: Print the multiplication table of a given number.

Solution:

public class MultiplicationTable {

public static void printTable(int num) {

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

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

}
}

46. Find Factorial using Recursion

Problem: Calculate factorial of a number using recursion.

Solution:

public class FactorialRecursion {

public static long factorial(int n) {

if (n <= 1) return 1;

return n * factorial(n - 1);

47. Find Maximum Difference in an Array

Problem: Find the maximum difference between two elements in an array.

Solution:

public class MaxDifference {

public static int findMaxDiff(int[] arr) {

int maxDiff = Integer.MIN_VALUE;

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

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

maxDiff = Math.max(maxDiff, arr[j] - arr[i]);

return maxDiff;

48. Print Fibonacci Series up to N terms

Problem: Print Fibonacci series for n terms.

Solution:

public class FibonacciSeries {

public static void printFibonacci(int n) {

int a = 0, b = 1;
for (int i = 0; i < n; i++) {

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

int c = a + b;

a = b;

b = c;

49. Print Prime Numbers in a Range

Problem: Print all prime numbers between two numbers.

Solution:

public class PrimeInRange {

public static void printPrimes(int start, int end) {

for (int i = start; i <= end; i++) {

if (isPrime(i)) System.out.print(i + " ");

private static boolean isPrime(int n) {

if (n <= 1) return false;

for (int i = 2; i <= Math.sqrt(n); i++) {

if (n % i == 0) return false;

return true;

50. Print Armstrong Numbers in a Range

Problem: Print all Armstrong numbers in a given range.

Solution:

public class ArmstrongInRange {

public static void printArmstrong(int start, int end) {


for (int num = start; num <= end; num++) {

int sum = 0, temp = num, n = String.valueOf(num).length();

while (temp > 0) {

sum += Math.pow(temp % 10, n);

temp /= 10;

if (sum == num) System.out.print(num + " ");

51. Find Sum of Digits

Problem: Find the sum of the digits of a number.

Solution:

public class SumOfDigits {

public static int sumDigits(int num) {

int sum = 0;

while (num != 0) {

sum += num % 10;

num /= 10;

return sum;

52. Print GCD of Two Numbers

Problem: Find the GCD of two numbers.

Solution:

public class GCD {

public static int findGCD(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;
a = temp;

return a;

53. Convert String to Integer

Problem: Convert a string to an integer.

Solution:

public class StringToInteger {

public static int convert(String str) {

return Integer.parseInt(str);

54. Find LCM of Two Numbers

Problem: Find the LCM of two numbers.

Solution:

public class LCM {

public static int findLCM(int a, int b) {

return (a * b) / findGCD(a, b);

private static int findGCD(int a, int b) {

if (b == 0) return a;

return findGCD(b, a % b);

55. Print All Factors of a Number

Problem: Print all factors of a given number.

Solution:

public class Factors {

public static void printFactors(int num) {


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

if (num % i == 0) System.out.print(i + " ");

56. Find Second Largest Number in an Array

Problem: Find the second largest number in an array.

Solution:

public class SecondLargest {

public static int findSecondLargest(int[] arr) {

int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE;

for (int num : arr) {

if (num > max) {

secondMax = max;

max = num;

} else if (num > secondMax && num < max) {

secondMax = num;

return secondMax;

57. Remove Vowels from a String

Problem: Remove all vowels from a given string.

Solution:

public class RemoveVowels {

public static String removeVowels(String str) {

return str.replaceAll("[aeiouAEIOU]", "");

58. Find Length of String without length()


Problem: Find string length without using length() method.

Solution:

public class StringLength {

public static int findLength(String str) {

int length = 0;

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

length++;

return length;

59. Count Words in a Sentence

Problem: Count the number of words in a sentence.

Solution:

public class WordCount {

public static int countWords(String sentence) {

if (sentence == null || sentence.trim().isEmpty()) return 0;

return sentence.trim().split("\\s+").length;

60. Find Unique Elements in an Array

Problem: Print unique elements in an array.

Solution:

import java.util.HashSet;

public class UniqueElements {

public static void printUnique(int[] arr) {

HashSet<Integer> set = new HashSet<>();

for (int num : arr) {

set.add(num);

}
for (int num : set) {

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

61. Reverse Each Word in a String

Problem: Reverse each word in a given string.

Solution:

public class ReverseWords {

public static String reverseEachWord(String str) {

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

StringBuilder result = new StringBuilder();

for (String word : words) {

result.append(new StringBuilder(word).reverse()).append(" ");

return result.toString().trim();

62. Print All ASCII Values

Problem: Print ASCII values of all alphabets.

Solution:

public class ASCIIValues {

public static void main(String[] args) {

for (char c = 'A'; c <= 'Z'; c++) {

System.out.println(c + ": " + (int)c);

63. Calculate Simple Interest

Problem: Calculate simple interest.

Solution:
public class SimpleInterest {

public static double calculate(double p, double r, double t) {

return (p * r * t) / 100;

64. Find Missing Number in Array

Problem: Find missing number in an array of n-1 integers.

Solution:

public class MissingNumber {

public static int findMissingNumber(int[] arr, int n) {

int sum = n * (n + 1) / 2;

for (int num : arr) sum -= num;

return sum;

65. Count Vowels and Consonants

Problem: Count the vowels and consonants in a string.

Solution:

public class VowelsConsonants {

public static void count(String str) {

int vowels = 0, consonants = 0;

str = str.toLowerCase();

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

if (Character.isLetter(c)) {

if ("aeiou".indexOf(c) != -1) vowels++;

else consonants++;

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

}
66. Find Maximum Occurring Character

Problem: Find the maximum occurring character in a string.

Solution:

import java.util.HashMap;

public class MaxOccurringChar {

public static char findMaxChar(String str) {

HashMap<Character, Integer> map = new HashMap<>();

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

map.put(c, map.getOrDefault(c, 0) + 1);

char maxChar = ' ';

int maxCount = 0;

for (char c : map.keySet()) {

if (map.get(c) > maxCount) {

maxCount = map.get(c);

maxChar = c;

return maxChar;

67. Check Armstrong Number for Any Length

Problem: Check if a number is an Armstrong number.

Solution:

public class ArmstrongNumber {

public static boolean isArmstrong(int num) {

int original = num, sum = 0;

int length = String.valueOf(num).length();

while (num != 0) {

int digit = num % 10;


sum += Math.pow(digit, length);

num /= 10;

return sum == original;

68. Find Frequency of Each Character

Problem: Count frequency of each character in a string.

Solution:

import java.util.HashMap;

public class CharFrequency {

public static void countFreq(String str) {

HashMap<Character, Integer> map = new HashMap<>();

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

map.put(c, map.getOrDefault(c, 0) + 1);

map.forEach((k, v) -> System.out.println(k + ": " + v));

69. Reverse Number Recursively

Problem: Reverse a number using recursion.

Solution:

public class ReverseNumberRecursive {

public static int reverse(int num, int rev) {

if (num == 0) return rev;

rev = rev * 10 + num % 10;

return reverse(num / 10, rev);

70. Calculate Compound Interest


Problem: Calculate compound interest.

Solution:

public class CompoundInterest {

public static double calculate(double p, double r, double t) {

return p * Math.pow((1 + r / 100), t) - p;

71. Convert Decimal to Hexadecimal

Problem: Convert a decimal number to hexadecimal.

Solution:

public class DecimalToHexadecimal {

public static String convert(int num) {

return Integer.toHexString(num).toUpperCase();

72. Convert Hexadecimal to Decimal

Problem: Convert a hexadecimal number to decimal.

Solution:

public class HexadecimalToDecimal {

public static int convert(String hex) {

return Integer.parseInt(hex, 16);

73. Check Harshad Number

Problem: Check if a number is a Harshad number (divisible by the sum of its digits).

Solution:

public class HarshadNumber {

public static boolean isHarshad(int num) {

int sum = 0, temp = num;

while (temp > 0) {

sum += temp % 10;


temp /= 10;

return num % sum == 0;

74. Convert Binary to Octal

Problem: Convert a binary number to octal.

Solution:

public class BinaryToOctal {

public static String convert(String binary) {

int decimal = Integer.parseInt(binary, 2);

return Integer.toOctalString(decimal);

75. Find Sum of Series 1² + 2² + 3² + ... + n²

Problem: Find the sum of squares up to n.

Solution:

public class SumOfSquares {

public static int sum(int n) {

return (n * (n + 1) * (2 * n + 1)) / 6;

76. Check Duck Number

Problem: Check if a number is a Duck number (contains zero but not starting with zero).

Solution:

public class DuckNumber {

public static boolean isDuck(String num) {

return num.indexOf('0') > 0;

77. Find Factorial using Recursion


Problem: Find the factorial of a number using recursion.

Solution:

public class FactorialRecursion {

public static long factorial(int n) {

if (n <= 1) return 1;

return n * factorial(n - 1);

78. Generate Fibonacci Series up to N Terms

Problem: Print the Fibonacci series up to n terms.

Solution:

public class FibonacciSeries {

public static void generate(int n) {

int a = 0, b = 1;

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

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

int next = a + b;

a = b;

b = next;

79. Find Power of a Number using Recursion

Problem: Calculate power (x^y) using recursion.

Solution:

public class PowerRecursion {

public static int power(int x, int y) {

if (y == 0) return 1;

return x * power(x, y - 1);

}
80. Find HCF (GCD) of Two Numbers

Problem: Find the Highest Common Factor (HCF) of two numbers.

Solution:

public class HCF {

public static int findHCF(int a, int b) {

if (b == 0) return a;

return findHCF(b, a % b);

81. Find LCM of Two Numbers

Problem: Find the Least Common Multiple (LCM) of two numbers.

Solution:

public class LCM {

public static int findLCM(int a, int b) {

return (a * b) / findHCF(a, b);

private static int findHCF(int a, int b) {

if (b == 0) return a;

return findHCF(b, a % b);

82. Reverse a Linked List

Problem: Reverse a singly linked list.

Solution:

class Node {

int data;

Node next;

Node(int data) { this.data = data; }

}
public class ReverseLinkedList {

public Node reverse(Node head) {

Node prev = null, current = head;

while (current != null) {

Node next = current.next;

current.next = prev;

prev = current;

current = next;

return prev;

83. Check if Two Strings are Anagrams

Problem: Check if two given strings are anagrams.

Solution:

import java.util.Arrays;

public class AnagramCheck {

public static boolean areAnagrams(String s1, String s2) {

char[] arr1 = s1.toCharArray();

char[] arr2 = s2.toCharArray();

Arrays.sort(arr1);

Arrays.sort(arr2);

return Arrays.equals(arr1, arr2);

84. Check Palindrome String

Problem: Check if a given string is palindrome.

Solution:

public class PalindromeString {

public static boolean isPalindrome(String s) {


int i = 0, j = s.length() - 1;

while (i < j) {

if (s.charAt(i++) != s.charAt(j--)) return false;

return true;

85. Find Missing Number in an Array

Problem: Find the missing number in an array containing numbers from 1 to n.

Solution:

public class MissingNumber {

public static int findMissing(int[] arr, int n) {

int sum = n * (n + 1) / 2;

for (int num : arr) sum -= num;

return sum;

86. Find First Non-Repeated Character in a String

Problem: Find the first non-repeating character in a string.

Solution:

import java.util.LinkedHashMap;

public class FirstNonRepeatedChar {

public static char find(String s) {

LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();

for (char c : s.toCharArray())

map.put(c, map.getOrDefault(c, 0) + 1);

for (var entry : map.entrySet()) {

if (entry.getValue() == 1) return entry.getKey();

return '\0';
}

87. Count Occurrences of a Character in a String

Problem: Count the number of occurrences of a character in a given string.

Solution:

public class CharacterOccurrence {

public static int count(String s, char c) {

int count = 0;

for (char ch : s.toCharArray()) {

if (ch == c) count++;

return count;

88. Find Length of Longest Word in a Sentence

Problem: Find the length of the longest word in a sentence.

Solution:

public class LongestWordLength {

public static int find(String sentence) {

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

int maxLen = 0;

for (String word : words) {

if (word.length() > maxLen) maxLen = word.length();

return maxLen;

89. Calculate Area of a Triangle (using Heron's formula)

Problem: Find the area of a triangle using sides a, b, c.

Solution:

public class TriangleArea {


public static double area(double a, double b, double c) {

double s = (a + b + c) / 2;

return Math.sqrt(s * (s - a) * (s - b) * (s - c));

90. Find Armstrong Numbers in a Range

Problem: Find all Armstrong numbers between 1 and 1000.

Solution:

public class ArmstrongRange {

public static void findArmstrong() {

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

int num = i, sum = 0, digits = String.valueOf(i).length();

while (num > 0) {

sum += Math.pow(num % 10, digits);

num /= 10;

if (sum == i) System.out.println(i);

91. Find Common Elements in Two Arrays

Problem: Find common elements between two integer arrays.

Solution:

import java.util.*;

public class CommonElements {

public static Set<Integer> find(int[] arr1, int[] arr2) {

Set<Integer> set1 = new HashSet<>();

Set<Integer> result = new HashSet<>();

for (int n : arr1) set1.add(n);

for (int n : arr2) {


if (set1.contains(n)) result.add(n);

return result;

92. Sum of Digits in a Number

Problem: Find the sum of all digits in a given number.

Solution:

public class SumOfDigits {

public static int sumDigits(int num) {

int sum = 0;

while (num > 0) {

sum += num % 10;

num /= 10;

return sum;

93. Find All Factors of a Number

Problem: Print all factors of a given number.

Solution:

public class Factors {

public static void printFactors(int num) {

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

if (num % i == 0) System.out.print(i + " ");

94. Check if Number is a Perfect Number

Problem: Check whether a number is a perfect number (sum of its proper divisors equals the
number).
Solution:

public class PerfectNumber {

public static boolean isPerfect(int num) {

int sum = 0;

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

if (num % i == 0) sum += i;

return sum == num;

95. Find Frequency of Each Character in a String

Problem: Count frequency of each character in a string.

Solution:

import java.util.HashMap;

public class CharFrequency {

public static void frequency(String s) {

HashMap<Character, Integer> freqMap = new HashMap<>();

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

freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);

System.out.println(freqMap);

96. Remove Duplicate Characters from a String

Problem: Remove duplicate characters and print a string with unique characters.

Solution:

public class RemoveDuplicates {

public static String removeDup(String s) {

StringBuilder sb = new StringBuilder();

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


char c = s.charAt(i);

if (sb.indexOf(String.valueOf(c)) == -1) sb.append(c);

return sb.toString();

97. Convert String to Title Case

Problem: Convert a given sentence to title case.

Solution:

public class TitleCase {

public static String convert(String sentence) {

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

StringBuilder sb = new StringBuilder();

for (String word : words) {

sb.append(Character.toUpperCase(word.charAt(0)))

.append(word.substring(1).toLowerCase()).append(" ");

return sb.toString().trim();

98. Find Largest Prime Factor of a Number

Problem: Find the largest prime factor of a given number.

Solution:

public class LargestPrimeFactor {

public static long largestPrimeFactor(long num) {

long factor = 2;

while (factor * factor <= num) {

if (num % factor == 0) num /= factor;

else factor++;

return num;
}

99. Find Product of All Digits in a Number

Problem: Multiply all digits of a number.

Solution:

public class ProductOfDigits {

public static int product(int num) {

int product = 1;

while (num > 0) {

product *= (num % 10);

num /= 10;

return product;

100. Print a Floyd's Triangle

Problem: Print Floyd's Triangle with n rows.

Solution:

public class FloydTriangle {

public static void printTriangle(int n) {

int num = 1;

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

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

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

System.out.println();

Integration Cloud
Problem: Integrate three simulated payment gateways, choose the fastest response.

class PaymentGateway {

String name;

int responseTime; // in milliseconds

PaymentGateway(String name, int responseTime) {

this.name = name;

this.responseTime = responseTime;

public class FastestGateway {

public static void main(String[] args) {

PaymentGateway[] gateways = {

new PaymentGateway("GatewayA", 500),

new PaymentGateway("GatewayB", 300),

new PaymentGateway("GatewayC", 450)

};

PaymentGateway fastest = gateways[0];

for (PaymentGateway g : gateways) {

if (g.responseTime < fastest.responseTime) fastest = g;

System.out.println("Fastest gateway is: " + fastest.name);

App Cloud

Problem: Register/login system with note storage.

import java.util.*;

class User {

String username, password;

List<String> notes = new ArrayList<>();


}

public class AppCloudSimulation {

static Map<String, User> users = new HashMap<>();

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Register: Username?");

String user = sc.nextLine();

System.out.println("Password?");

String pass = sc.nextLine();

User u = new User(); u.username=user; u.password=pass;

users.put(user, u);

System.out.println("Login Username?");

String loginUser = sc.nextLine();

System.out.println("Password?");

String loginPass = sc.nextLine();

if(users.containsKey(loginUser) && users.get(loginUser).password.equals(loginPass)) {

System.out.println("Add Note:");

String note = sc.nextLine();

users.get(loginUser).notes.add(note);

System.out.println("Notes: " + users.get(loginUser).notes);

} else System.out.println("Invalid login.");

IoT Cloud

Problem: Simulate temperature sensor data.

import java.util.*;

public class IoTCloud {

public static void main(String[] args) {

Random rand = new Random();

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


int temp = 20 + rand.nextInt(30);

System.out.println("Device " + device + ": Temp = " + temp);

if (temp > 40) System.out.println("ALERT: High temperature!");

Manufacturing Cloud

Problem: Track production and defect rate.

public class ManufacturingCloud {

public static void main(String[] args) {

int produced = 1000, defective = 47;

double efficiency = ((produced - defective) / (double) produced) * 100;

System.out.println("Efficiency: " + efficiency + "%");

Financial Service Cloud

Problem: Basic banking system.

class BankAccount {

String accName;

double balance;

BankAccount(String name, double bal) { accName=name; balance=bal; }

void deposit(double amt) { balance += amt; }

void withdraw(double amt) { if (balance >= amt) balance -= amt; }

void showBalance() { System.out.println("Balance: " + balance); }

public class BankSystem {

public static void main(String[] args) {

BankAccount acc = new BankAccount("John", 1000);

acc.deposit(500);
acc.withdraw(200);

acc.showBalance();

Education Cloud

Problem: Store and display student grades.

import java.util.*;

public class EducationCloud {

public static void main(String[] args) {

Map<String, Integer> grades = new HashMap<>();

grades.put("John", 85);

grades.put("Emma", 92);

grades.put("Liam", 78);

grades.forEach((k, v) -> System.out.println(k + ": " + v));

Non-Profit Cloud

Problem: Track donations.

import java.util.*;

public class NonProfitCloud {

public static void main(String[] args) {

Map<String, Double> donations = new HashMap<>();

donations.put("DonorA", 1000.0);

donations.put("DonorB", 500.0);

donations.forEach((name, amount) -> System.out.println(name + " donated: $" + amount));

Marketing Cloud

Problem: Send marketing emails simulation.


import java.util.*;

public class MarketingCloud {

public static void main(String[] args) {

List<String> emails = Arrays.asList("[email protected]", "[email protected]", "[email protected]");

for (String email : emails) {

System.out.println("Sending marketing email to: " + email);

Health Cloud

Problem: Patient record management.

import java.util.*;

class Patient {

String name;

int age;

String condition;

Patient(String n, int a, String c) { name=n; age=a; condition=c; }

public class HealthCloud {

public static void main(String[] args) {

List<Patient> patients = new ArrayList<>();

patients.add(new Patient("John", 45, "Diabetes"));

patients.add(new Patient("Emma", 30, "Asthma"));

patients.forEach(p -> System.out.println(p.name + ", Age: " + p.age + ", Condition: " +
p.condition));

Vaccine Cloud

Problem: Track vaccine doses.

import java.util.*;

public class VaccineCloud {


public static void main(String[] args) {

Map<String, Integer> vaccineDoses = new HashMap<>();

vaccineDoses.put("Pfizer", 1200);

vaccineDoses.put("Moderna", 800);

vaccineDoses.forEach((k, v) -> System.out.println(k + " doses: " + v));

You might also like