Introduction
Java’s versatility is one of its best qualities. You can discover that the same problem can be solved in several ways. Here are some beginner-friendly Java code challenges. Begin your learning journey with our Java course program.
Java Code Challenges and Solutions
Here are some Java code challenges with coding solutions.
Word Reversal
Challenge: A string of words serves as the challenge’s input, and the words in reverse with the letters in their original order should be the output.
Example: SLA is Best
Best is SLA
Code Solution:
import java.util.regex.Pattern;
public class Exp {
static String reverseWords(String str)
{
Pattern pattern = Pattern.compile(“\\s”);
String[] temp = pattern.split(str);
String result = “”;
for (int i = 0; i < temp.length; i++) {
if (i == temp.length – 1)
result = temp[i] + result;
else
result = ” ” + temp[i] + result;
}
return result;
}
public static void main(String[] args)
{
String s1 = “SLA is Best”;
System.out.println(reverseWords(s1));
String s2 = “Java Programming”;
System.out.println(reverseWords(s2));
}
}
Output
Best is SLA
Programming Java
Palindrome Challenge
A word, phrase, number, or other character sequence that reads the same both forward and backward is called a palindrome. Writing a program to ascertain whether a given string or number is a palindrome is a classic programming exercise.
Examples: radar, level, madam
Challenge: To construct a Java application that checks for palindromes.
Code Solution:
class Main {
public static void main(String[] args) {
String str = “Radar”, reverseStr = “”;
int strLength = str.length();
for (int i = (strLength – 1); i >=0; –i) {
reverseStr = reverseStr + str.charAt(i);
}
if (str.toLowerCase().equals(reverseStr.toLowerCase())) {
System.out.println(str + ” is a Palindrome String.”);
}
else {
System.out.println(str + ” is not a Palindrome String.”);
}
}
}
Output
Radar is a Palindrome String.
Find the Word
Challenge: Determine the second-to-last word in a given input string of words.
For example, “Java” should be returned when the input is “I love Java.”
Code Solution:
public class Main {
public static void main(String[] args){
String str = “I love Java”;
System.out.println(str);
String find = “Java”;
boolean val = str.contains(find);
if(val)
System.out.println(“String found: “+find);
else
System.out.println(“string not found”);
}
}
Output
I love Java
String found: Java
Learn the fundamentals with our Java tutorial for beginners.
Anagrams
Challenge: If two words have the same letters but are arranged differently, they are anagrams. A few instances of anagram pairs are as follows:
“Silent” and “listen”
“Brainy” and “binary”
“Paris” and “pairs”
If two strings are provided as input, return a Boolean TRUE indicating that they are anagrams.
Code Solution:
import java.util.Arrays;
public class AnagramStringExample1
{
static void isAnagram(String str1, String str2)
{
String s1 = str1.replaceAll(“\\s”, “”);
String s2 = str2.replaceAll(“\\s”, “”);
boolean status = true;
if (s1.length() != s2.length())
{
status = false;
}
else
{
char[] arrayS1 = s1.toLowerCase().toCharArray();
char[] arrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(arrayS1);
Arrays.sort(arrayS2);
status = Arrays.equals(arrayS1, arrayS2);
}
if (status)
{
System.out.println(s1 + ” and ” + s2 + ” are anagrams”);
}
else
{
System.out.println(s1 + ” and ” + s2 + ” are not anagrams”);
}
}
public static void main(String args[])
{
isAnagram(“HEART”, “EARTH”);
isAnagram(“TRIANGLE”, “INTEGRAL”);
isAnagram(“TOSS”, “SHOT”);
}
}
Output:
HEART and EARTH are anagrams
TRIANGLE and INTEGRAL are anagrams
TOSS and SHOT are not anagrams
Pangrams Challenge
A statement that uses every one of the 26 letters in the English alphabet is called a pangram.
Example: “The quick brown fox jumps over the lazy dog”
Challenge: Make a pangram checker that, if an input string is a pangram, returns the Boolean TRUE; if not, it returns the FALSE.
Code Solution:
public class PangramStringExample1
{
static int size = 26;
static boolean isLetter(char ch)
{
if (!Character.isLetter(ch))
return false;
return true;
}
static boolean containsAllLetters(String str, int len)
{
str = str.toLowerCase();
boolean[] present = new boolean[size];
for (int i = 0; i < len; i++)
{
if (isLetter(str.charAt(i)))
{
int letter = str.charAt(i) – ‘a’;
present[letter] = true;
}
}
for (int i = 0; i < size; i++)
{
if (!present[i])
return false;
}
return true;
}
public static void main(String args[])
{
String str = “Pack my box with five dozen liquor jugs”;
int len = str.length();
if (containsAllLetters(str, len))
System.out.println(“The given string is a pangram string.”);
else
System.out.println(“The given string is not a pangram string.”);
}
}
Output:
The given string is a pangram string.
Try more Java programs with our top Java project ideas.
Number Reversal Challenge
Challenge: Return the number in reverse for an input number. Thus, a 3956 input ought to yield 6593.
Code Solution:
class Main {
public static void main(String[] args) {
int num = 1234, reversed = 0;
System.out.println(“Original Number: ” + num)
while(num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println(“Reversed Number: ” + reversed);
}
}
Output
Reversed Number: 4321
Armstrong Number Challenge
Challenge: A whole number that equals the sum of its digits raised to the power of the entire number of digits is known as an Armstrong number.
It has three digits and is equal to 13 + 53 + 33, 153 is an Armstrong number.
Because 8208 = 84 + 24 + 04 + 84, the four-digit number is also an Armstrong number.
Code Solution:
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + ” is an Armstrong number.”);
else
System.out.println(number + ” is not an Armstrong number.”);
}
}
Output
371 is an Armstrong number.
Product Maximization Challenge
Challenge: Determine which two, out of a given input array of numbers, produce the largest product. The two numbers in the array and their product should be included in the output.
Code Solution:
public class ProductMaximization {
public static int maximizeProduct(int[] weights, int[] values, int capacity) {
int n = weights.length;
int[][] dp = new int[n + 1][capacity + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= capacity; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (weights[i – 1] <= j) {
dp[i][j] = Math.max(values[i – 1] + dp[i – 1][j – weights[i – 1]], dp[i – 1][j]);
} else {
dp[i][j] = dp[i – 1][j];
}
}
}
return dp[n][capacity];
}
public static void main(String[] args) {
int[] weights = {2, 3, 4, 5};
int[] values = {3, 4, 5, 6};
int capacity = 7;
int maxProduct = maximizeProduct(weights, values, capacity);
System.out.println(“Maximum product value: ” + maxProduct);
}
}
Output:
Maximum product value: 10
Review your skills with our Java interview questions and answers.
Prime Number Checker Challenge
Challenge: Any whole number larger than one that has only one factor and itself is a prime number.
For instance, 7 is only divisible by 1 and 7, making it a prime number.
Code Solution:
public class Main {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
if (num == 0 || num == 1) {
flag = true;
}
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
System.out.println(num + ” is a prime number.”);
else
System.out.println(num + ” is not a prime number.”);
}
}
Output
29 is a prime number.
Prime Factorization Challenge
Challenge: All of the integers below a given number that are divisible by both the number and 1 are its prime factors.
For instance, 1, 2, 3, 4, 6, and 12 are the prime factors of 12.
Code Solution:
public class PrimeFactorProgram {
public static void findPrimeFactors(int num) {
while (num % 2 == 0) {
System.out.print(2 + ” “); // Print 2 as a prime factor
num /= 2; // Divide num by 2
}
for (int i = 3; i <= Math.sqrt(num); i += 2) {
while (num % i == 0) {
System.out.print(i + ” “); // Print i as a prime factor
num /= i; // Divide num by i
}
}
if (num > 2) {
System.out.print(num);
}
}
public static void main(String[] args) {
int num = 56; // Define the number to find prime factors
System.out.print(“Prime factors of ” + num + ” are: “);
findPrimeFactors(num); // Call the method to find and print prime factors
}
}
Output:
Prime factors of 56 are: 2 2 2 7
Choose your desired career with our wide range of software training courses.
Conclusion
Code challenges are not only an enjoyable and stress-free method to assess your programming language skills, but they also help you get ready for the interview process. Enroll in our core Java training in Chennai if you want to work in a field where Java skills are required.