Core Java Coding Challenges and Tested Solutions
Java is one of the cornerstones of contemporary programming, but conquering its intricacies is not just a matter of theory. Our set of Core Java coding exercises aims to fill in the gaps between theory and application, allowing you to reinforce basic concepts and problem-solving techniques. Every challenge offers a hands-on experience to become more confident and ready for practical situations. Are you ready to advance your skills to the next level? Download our Core Java course syllabus to understand how you can become proficient in the language.
Core Java Coding Challenges and Solutions
Here are the challenges in core Java with tested coding solutions:
Palindrome Checker
Challenge: Create a Java application that determines whether a provided string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward.
Coding Solution:
public class PalindromeChecker {
public static boolean isPalindrome(String str) {
String reversedStr = new StringBuilder(str).reverse().toString();
return str.equalsIgnoreCase(reversedStr);
}
public static void main(String[] args) {
String test1 = “madam”;
String test2 = “level”;
String test3 = “hello”;
System.out.println(test1 + ” is a palindrome: ” + isPalindrome(test1));
System.out.println(test2 + ” is a palindrome: ” + isPalindrome(test2));
System.out.println(test3 + ” is a palindrome: ” + isPalindrome(test3));
}
}
This easy exercise familiarizes you with String manipulation and the StringBuilder class, which is more effective for string modification than the String class. In apps, palindrome verification is used as a basis for checking data.
For example, in a game app, a user’s name or a custom code could be checked using a palindrome verification. Likewise, in a puzzle game, this same code could be utilized to check a completed level.
FizzBuzz
Challenge: Create a program that will print numbers 1 to 100. For multiples of three, print “Fizz” in place of the number. Print “Buzz.” for multiples of five. When a number is a multiple of three and five, print “FizzBuzz.”
Coding Solution:
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean divisibleBy3 = (i % 3 == 0);
boolean divisibleBy5 = (i % 5 == 0);
if (divisibleBy3 && divisibleBy5) {
System.out.println(“FizzBuzz”);
} else if (divisibleBy3) {
System.out.println(“Fizz”);
} else if (divisibleBy5) {
System.out.println(“Buzz”);
} else {
System.out.println(i);
}
}
}
}
FizzBuzz is a well-known interview problem that evaluates your level of familiarity with conditional statements (if-else if-else) and loops (for loop). It’s not only a silly problem; it’s a test of elementary programming logic. In actual applications, the same logic is utilized for operations such as:
- Data Processing: Generating reports where specific conditions call forth individual labels or activities.
- Rule-based Systems: In a logistics system, a package would be marked “Fragile” or “Urgent” depending on its weight and where it is headed.
Recommended: Core Java Course Online.
Factorial Calculation
Challenge: Write a Java program to find the factorial of a non-negative integer passed as input. The product of all positive integers that are less than or equal to a given number n is its factorial.
Coding Solution:
public class FactorialCalculator {
public static long calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException(“Number must be non-negative.”);
}
long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int number = 5;
try {
long factorial = calculateFactorial(number);
System.out.println(“The factorial of ” + number + ” is: ” + factorial);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
This exercise introduces looping for mathematical calculations and exception handling (try-catch), an important principle for constructing robust applications. Factorial computation is ubiquitous in statistical and probability programs.
For instance, in a data analysis program, you may have to compute permutations and combinations to simulate compound outcomes. It is also a precursor to learning recursive functions, a more sophisticated but elegant method of solving this problem.
Recommended: Core Java Course Tutorial for Beginners.
Vowel Counter
Challenge: Write a Java program that determines the number of vowels in a string. Vowels are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (case-insensitive).
Coding Solution:
public class VowelCounter {
public static int countVowels(String str) {
int count = 0;
String lowerStr = str.toLowerCase();
for (int i = 0; i < lowerStr.length(); i++) {
char ch = lowerStr.charAt(i);
if (ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String text = “Hello World! This is a test string.”;
int vowelCount = countVowels(text);
System.out.println(“Number of vowels: ” + vowelCount);
}
}
This exercise teaches you how to loop through a string using a loop and refer to individual characters using charAt(). It also impresses the need to address case sensitivity with toLowerCase(). This simple string processing pattern is a foundation for many applications, such as:
- Text Analysis: Examining user reviews or social media comments to discern sentiment or extract keywords.
- Natural Language Processing (NLP): A building block for processing text to feed into more advanced tasks such as translation or chatbots.
- Data Cleaning: Pre-processing text data prior to storage in a database.
Simple Bank Account
Challenge: Create a basic BankAccount class with an account number and balance fields, and deposit() and withdraw() methods.
Coding Solution:
public class BankAccount {
private String accountNumber;
private double balance;
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println(“Deposited ” + amount + “. New balance: ” + balance);
} else {
System.out.println(“Deposit amount must be positive.”);
}
}
public void withdraw(double amount) {
if (amount > 0 && balance >= amount) {
balance -= amount;
System.out.println(“Withdrew ” + amount + “. New balance: ” + balance);
} else {
System.out.println(“Withdrawal failed. Insufficient funds or invalid amount.”);
}
}
public static void main(String[] args) {
BankAccount myAccount = new BankAccount(“123456789”, 500.00);
myAccount.deposit(250.00);
myAccount.withdraw(100.00);
myAccount.withdraw(800.00); // This should fail
}
}
This exercise is your entry point to Object-Oriented Programming (OOP). You discover how to define a class (BankAccount) with fields (attributes) and methods (behaviors). The private usage emphasizes encapsulation, a central OOP concept that defends data against improper access. This paradigm is the basis for all software handling real-world objects, e.g.:
- E-commerce Systems: An Order class and a calculateTotal() method.
- Student Management Systems: A Student class with name and ID fields.
- Inventory Management: An Item class with price and quantity fields.
Recommended: Advanced Java Course Online.
Fibonacci Sequence
Challenge: Write a Java program that generates and prints the first n numbers of the Fibonacci sequence. In this sequence, every number is the sum of the two numbers before it, beginning at 0 and 1.
Coding Solution:
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
long[] fibArray = new long[n];
if (n >= 1) {
fibArray[0] = 0;
}
if (n >= 2) {
fibArray[1] = 1;
}
for (int i = 2; i < n; i++) {
fibArray[i] = fibArray[i – 1] + fibArray[i – 2];
}
System.out.println(“Fibonacci sequence up to ” + n + ” terms:”);
for (long num : fibArray) {
System.out.print(num + ” “);
}
}
}
This problem trains you on iterative solutions and array manipulation. The Fibonacci sequence is more than a curiosity in mathematics; it shows up in nature, in finance, and in computer science. In programming, it’s utilized in searching and sorting algorithms, and as a traditional problem for learning recursion, where a function recursively calls itself.
Array Sorting
Challenge: Write a Java program that sorts an array of integers in ascending order. You should use a basic sorting algorithm, such as Bubble Sort.
Code Solution:
public class ArraySorter {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n – 1; i++) {
for (int j = 0; j < n – i – 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
System.out.println(“Original array:”);
for (int num : numbers) {
System.out.print(num + ” “);
}
bubbleSort(numbers);
System.out.println(“\nSorted array:”);
for (int num : numbers) {
System.out.print(num + ” “);
}
}
}
This is a basic exercise for learning algorithms and data structures. Although Java’s Arrays.sort() is many times more efficient in reality, doing a simple sort like Bubble Sort by scratch makes you understand the principle of sorting and how to operate on array elements. Sorting is utilized everywhere from showing search results to sorting financial information in a spreadsheet.
Recommended: Core Java Interview Questions and Answers.
Prime Number Checker
Challenge: Create a Java program to identify whether a specified positive integer is a prime number. Any natural number greater than one that cannot be the product of two smaller natural numbers is called a prime number.
Coding Solution:
public class PrimeNumberChecker {
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;
}
public static void main(String[] args) {
int number1 = 17;
int number2 = 12;
System.out.println(number1 + ” is a prime number: ” + isPrime(number1));
System.out.println(number2 + ” is a prime number: ” + isPrime(number2));
}
}
This problem is an excellent exercise in loops and logical reasoning in mathematics. The call to Math.sqrt(n) is an important optimization that shows awareness of efficiency. Prime numbers play an important role in cryptography and data security for generating secure encryption keys, like those used in public-key cryptography (for example, the RSA algorithm).
Reverse a String
Challenge: Reverse a string using Java without invoking built-in methods like StringBuilder.reverse().
Coding Solution:
public class StringReverser {
public static String reverseString(String str) {
char[] charArray = str.toCharArray();
int left = 0;
int right = charArray.length – 1;
while (left < right) {
// Swap characters
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++;
right–;
}
return new String(charArray);
}
public static void main(String[] args) {
String original = “Java programming”;
String reversed = reverseString(original);
System.out.println(“Original: ” + original);
System.out.println(“Reversed: ” + reversed);
}
}
This exercise reinforces your knowledge of string-to-character array conversion and in-place manipulation. It’s a classic interview question that checks your algorithmic thinking, without your ability to use handy library functions. Reversing strings is applied in text editors to data manipulation for certain formats.
Explore: Java Professionals Salary for Freshers.
Largest Element in an Array
Challenge: Create a Java program to calculate the largest element of an array of integers.
Coding Solution:
public class LargestElement {
public static int findLargest(int[] arr) {
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException(“Array cannot be empty or null.”);
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
public static void main(String[] args) {
int[] numbers = {15, 27, 8, 33, 19, 42};
try {
int largest = findLargest(numbers);
System.out.println(“The largest element is: ” + largest);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
This basic problem is great for exercising array traversal and simple logic. It also teaches the significance of edge case consideration (e.g., an empty or null array).
This type of logic forms the foundation for bigger applications, such as the highest-priced item in an online catalog, determining the peak value from a sensor data stream, or determining maximum profits in a financial application.
Explore: All Software Training Courses.
Conclusion
By overcoming these challenges, you’ve acquired hands-on experience with fundamental Java constructs such as loops, conditionals, arrays, and string manipulation. This practical experience is critical to bridge the gap between theory and actual programming practice.
By completing these problems, you’ve established a solid foundation for more challenging projects and a software development career. To further speed up your learning and master advanced subject matter, take our in-depth Core Java course in Chennai and realize your full potential.