Software Training Institute in Chennai with 100% Placements – SLA Institute
⭐ Exclusive Summer Courses Offer ⭐ 💰 Flat ₹5,000 - ₹10,000 off on all courses 👨‍👩‍👧 Additional discounts for group enrollments 🎓 100% Placement Support 🏆 90,000+ Students Successfully Placed 🚀 Avail now! Limited seats only!
Java Challenges For Beginners - Softlogic Systems.
Share on your Social Media

Java Code Challenges and Solutions for Beginners

Published On: November 2, 2024

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. Explore our Java Course Syllabus to get started.

  1. Word Reversal
  2. Palindrome Challenge
  3. Find the Word
  4. Anagrams
  5. Pangrams Challenge
  6. Number Reversal Challenge
  7. Armstrong Number Challenge
  8. Product Maximization Challenge
  9. Prime Number Checker Challenge
  10. Prime Factorization Challenge

Here are some Java code challenges with coding solutions. 

1. 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

2. 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.

Students can learn easily at our Java Tutorial for beginners.

3. 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

Check your knowledge level with our smart Knowledge Assessment Tool

  • Instant skill evaluation with accurate scoring
  • Identify strengths and learning gaps easily
  • Designed for students and working professionals
  • Smart assessment to guide your career growth

Take Your Eligibility Report Instantly

4. 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

5. 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. 

6. 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

Ace your interviews with our Java interview questions and answers.

7. 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.

8. 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

9. 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.

Explore salary details at our Java Salary for Freshers and Experienced.

10. 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

1. What are the challenges of Java?

Java needs a lot of code for things. Writing Java code can be boring because of that. Also managing memory, slow start times and complicated syntax make it hard for new people to learn fast.

2. What is the most common error in Java?

The common error in Java is the NullPointerException. This error happens in Java when you try to use something that does not exist yet in Java. It is like trying to open a box in Java when the box’s empty.

3. Is Java a difficult language?

Java is not extremely difficult. It is not easy either. Java has a lot of rules that can be annoying at first. However these rules help you write code and make your Java programs work well.

4. What are the biggest challenges of programming?

Programmers have to deal with things. These include fixing errors, understanding code written by others, meeting deadlines and keeping up with new technologies. These are struggles for all programmers.

5. What are the challenges faced in a project?

Projects often have problems. These problems include planning, unclear goals, team members not talking well, scope creep and unexpected bugs. Usually people’s problems are harder to fix than ones.

6. What are the challenges of coding?

Coding requires thinking, being patient and always learning. Writing code that others can understand, avoiding mistakes and solving problems, under pressure makes coding both hard and very rewarding.

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. For more info on our training and placement feature, visit our Best Placement and Training Institute.

Share on your Social Media
Get Your Instant Job & Placement Eligibility
Report in Just 30 Seconds!
Below 30% - not Eligible (Needs Preparation)
30% – 70% - Partially Eligible (Needs Guidance)
Above 70% - Fully Eligible (Ready to Start)

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.