Java Programming Challenges
Java Programming Challenges
Here are a few moderate-level Java programming challenges that cover a variety of concepts,
including data structures, algorithms, and object-oriented programming principles:
Requirements:
Consider edge cases like ignoring spaces, punctuation, and case sensitivity.
java
1/62
}
}
Requirements:
Ensure that withdrawal operations are not allowed if the balance is insufficient.
java
class BankAccount {
private String accountNumber;
private double balance;
2/62
}
class Customer {
private String name;
private BankAccount bankAccount;
customer.displayDetails();
account.deposit(500);
account.withdraw(300);
customer.displayDetails();
}
}
Requirements:
java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
3/62
import java.util.List;
class Student {
private String name;
private double grade;
@Override
public String toString() {
return name + ": " + grade;
}
}
4/62
for (Student student : students) {
System.out.println(student);
}
}
}
4. Sudoku Validator
Create a program that validates whether a given 9x9 Sudoku puzzle solution is correct.
Requirements:
Check if each row, column, and 3x3 sub-grid contains digits 1 to 9 with no repetition.
java
import java.util.HashSet;
// Check column
if (board[j][i] != 0 && !columns.add(board[j][i])) {
return false;
}
5/62
}
}
}
return true;
}
These programs help to enhance your understanding of various concepts in Java, including
recursion, object-oriented programming, data structures, and the use of collections.
Here’s a list of 50 Java programming exercises, covering various topics like data structures,
algorithms, OOP concepts, and general programming skills. Each program includes a brief
description of its functionality:
Basic Programs
1. Hello World: Print "Hello, World!" to the console.
6/62
6. Sum of Digits: Calculate the sum of digits of a number.
8. Count Vowels and Consonants: Count the number of vowels and consonants in a string.
10. Basic Calculator: Implement a basic calculator for addition, subtraction, multiplication,
and division.
Intermediate Programs
11. Palindrome Checker: Check if a string is a palindrome.
17. Merge Two Arrays: Merge two sorted arrays into one.
Advanced Programs
21. Simple Banking System: Create a banking system with classes for BankAccount and
Customer .
24. Library Management System: Create a library management system with options to add,
remove, and view books.
25. Shopping Cart: Implement a shopping cart system with add, remove, and checkout
functionality.
7/62
27. Student Grade Management: Manage student grades and calculate averages using a
class.
29. Word Count in a File: Count the number of words in a text file.
30. File Encryption/Decryption: Implement a simple file encryption and decryption method.
34. Binary Tree Traversal: Implement pre-order, in-order, and post-order traversal for a
binary tree.
35. HashMap Implementation: Create a simple hash map with put and get methods.
37. Graph Representation: Represent a graph using adjacency list and perform depth-first
search (DFS).
38. Dynamic Array Implementation: Implement a dynamic array that resizes as needed.
39. Circular Linked List: Implement a circular linked list with basic operations.
Miscellaneous Programs
41. Simple To-Do List: Create a console-based to-do list application.
43. Currency Converter: Create a currency converter with static conversion rates.
44. Recipe Manager: Create a simple application to manage recipes (add, view, delete).
45. Simple Chat Application: Create a console-based chat application using sockets.
46. Weather Information Fetcher: Fetch and display weather information from an API.
48. XML Parser: Create a simple XML parser to extract data from an XML file.
8/62
50. Personal Diary Application: Create a console application to manage diary entries.
Focus on clean code, proper naming conventions, and commenting for better
readability.
Use version control (like Git) to track your progress and changes.
Explore different data structures and algorithms as you implement these programs.
If you need any specific implementation or help with a particular program, feel free to ask!
generate code
Here are implementations for a selection of the programs from the list of 50 Java
programming exercises. I've chosen a mix of basic, intermediate, and advanced programs to
showcase various concepts:
1. Hello World
java
2. Even or Odd
java
import java.util.Scanner;
9/62
System.out.println(number % 2 == 0 ? "Even" : "Odd");
}
}
java
import java.util.Scanner;
4. Factorial Calculation
java
import java.util.Scanner;
10/62
int number = scanner.nextInt();
System.out.println("Factorial: " + factorial(number));
}
}
5. Fibonacci Series
java
import java.util.Scanner;
6. Reverse a String
java
import java.util.Scanner;
11/62
}
}
7. Palindrome Checker
java
import java.util.Scanner;
java
import java.util.Scanner;
class BankAccount {
private String accountNumber;
private double balance;
12/62
System.out.println("Insufficient funds.");
} else {
balance -= amount;
System.out.println("Withdrew: $" + amount);
}
}
while (true) {
System.out.println("\nOptions: 1. Deposit 2. Withdraw 3. Check Balance
4. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
account.deposit(scanner.nextDouble());
break;
case 2:
System.out.print("Enter amount to withdraw: ");
account.withdraw(scanner.nextDouble());
break;
case 3:
System.out.println("Balance: $" + account.getBalance());
break;
case 4:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
13/62
}
}
import java.util.ArrayList;
import java.util.Scanner;
while (true) {
System.out.println("\nOptions: 1. Add Task 2. View Tasks 3. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter task: ");
input = scanner.nextLine();
todoList.add(input);
System.out.println("Task added.");
break;
case 2:
System.out.println("To-Do List:");
for (String task : todoList) {
System.out.println("- " + task);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
14/62
}
}
java
import java.io.*;
import java.net.*;
String message;
while ((message = input.readLine()) != null) {
System.out.println("Client: " + message);
output.println("Server: " + message);
}
15/62
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client
java
import java.io.*;
import java.net.*;
String message;
System.out.println("Connected to chat server. Type your messages:");
while ((message = consoleInput.readLine()) != null) {
output.println(message);
System.out.println(input.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
These implementations provide a solid foundation for each program. Feel free to expand
upon them, modify features, or ask for more specific code implementations for any other
programs from the list!
continue
Sure! Here are more Java programs from the list, covering additional exercises and
expanding upon various topics:
16/62
11. Armstrong Number Checker
java
import java.util.Scanner;
import java.util.Scanner;
17/62
}
import java.util.Arrays;
java
18/62
import java.util.Arrays;
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++];
}
}
import java.util.Scanner;
19/62
int[][] matrix2 = new int[rows][cols];
int[][] sum = new int[rows][cols];
System.out.println("Sum of matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
System.out.print(sum[i][j] + " ");
System.out.println();
}
}
}
import java.util.Scanner;
20/62
}
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public ChatClientGUI() {
JFrame frame = new JFrame("Chat Client");
textArea = new JTextArea(20, 50);
textField = new JTextField(50);
textArea.setEditable(false);
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
frame.add(textField, BorderLayout.SOUTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessage();
21/62
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
try {
socket = new Socket("localhost", 1234);
out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String message;
while ((message = in.readLine()) != null) {
textArea.append("Server: " + message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
java
import java.util.ArrayList;
import java.util.Scanner;
class Employee {
private String name;
22/62
private int id;
@Override
public String toString() {
return "ID: " + id + ", Name: " + name;
}
}
while (true) {
System.out.println("\nOptions: 1. Add Employee 2. View Employees 3.
Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter employee name: ");
String name = scanner.nextLine();
System.out.print("Enter employee ID: ");
int id = scanner.nextInt();
employees.add(new Employee(name, id));
System.out.println("Employee added.");
23/62
break;
case 2:
System.out.println("Employees:");
for (Employee emp : employees) {
System.out.println(emp);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
}
}
java
import java.util.ArrayList;
import java.util.Scanner;
class Book {
private String title;
@Override
public String toString() {
return title;
}
}
24/62
ArrayList<Book> books = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
int option;
while (true) {
System.out.println("\nOptions: 1. Add Book 2. View Books 3. Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter book title: ");
String title = scanner.nextLine();
books.add(new Book(title));
System.out.println("Book added.");
break;
case 2:
System.out.println("Books:");
for (Book book : books) {
System.out.println(book);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
}
}
}
java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
25/62
HashMap<String, String> questions = new HashMap<>();
questions.put("What is the capital of France?", "Paris");
questions.put("What is 2 + 2?", "4");
questions.put("What is the capital of Japan?", "Tokyo");
Feel free to run these Java programs to see how they work and modify them as needed. If
you need any further explanations or more examples, let me know!
continue
Here are more Java programs to continue the list, focusing on different topics and concepts:
java
import java.util.Scanner;
26/62
System.out.print("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}
java
import java.util.Scanner;
import java.util.Scanner;
27/62
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String reversed = new StringBuilder(str).reverse().toString();
import java.util.Scanner;
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
28/62
result = num1 / num2;
} else {
System.out.println("Division by zero is not allowed.");
return;
}
break;
default:
System.out.println("Invalid operation.");
return;
}
import java.util.Scanner;
29/62
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
30/62
System.out.println("Number of words: " + words.length);
}
}
import java.util.Scanner;
import java.util.Scanner;
31/62
long elapsedTime = endTime - startTime;
System.out.println("Elapsed Time: " + (elapsedTime / 1000.0) + " seconds");
}
}
java
import java.util.ArrayList;
import java.util.Scanner;
while (true) {
System.out.println("\nOptions: 1. Add Task 2. View Tasks 3. Exit");
System.out.print("Choose an option: ");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter task: ");
String task = scanner.nextLine();
toDoList.add(task);
System.out.println("Task added.");
break;
case 2:
System.out.println("Tasks:");
for (String t : toDoList) {
System.out.println(t);
}
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid option.");
}
32/62
}
}
}
import java.util.Arrays;
import java.util.Scanner;
java
import java.util.Scanner;
33/62
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}
java
import java.util.Scanner;
import java.util.Arrays;
import java.util.HashSet;
34/62
java
import java.util.Random;
import java.util.Scanner;
do {
System.out.print("Guess the number (1-100): ");
guess = scanner.nextInt();
attempts++;
import java.util.Scanner;
35/62
System.out.println("Reversed String: " + reversed);
}
}
import java.util.Scanner;
class BankAccount {
private String accountHolder;
private double balance;
36/62
String name = scanner.nextLine();
BankAccount account = new BankAccount(name);
int option;
do {
System.out.println("\nOptions: 1. Deposit 2. Withdraw 3. Check Balance
4. Exit");
option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.displayBalance();
break;
case 4:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 4);
}
}
java
import java.util.Scanner;
37/62
System.out.print("Enter a binary number: ");
String binaryString = scanner.nextLine();
int decimal = Integer.parseInt(binaryString, 2);
System.out.println("Decimal value: " + decimal);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
while (number != 0) {
sum += number % 10;
number /= 10;
}
38/62
}
}
java
import java.util.HashMap;
import java.util.Scanner;
java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
39/62
while (true) {
System.out.print("Vote for a candidate (A/B/C or Exit to finish): ");
vote = scanner.nextLine().toUpperCase();
if (vote.equals("EXIT")) {
break;
}
switch (vote) {
case "A":
candidates.put("Candidate A", candidates.get("Candidate A") +
1);
break;
case "B":
candidates.put("Candidate B", candidates.get("Candidate B") +
1);
break;
case "C":
candidates.put("Candidate C", candidates.get("Candidate C") +
1);
break;
default:
System.out.println("Invalid vote.");
}
}
System.out.println("Voting Results:");
for (Map.Entry<String, Integer> entry : candidates.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " votes");
}
}
}
java
import java.util.Scanner;
40/62
public static void main(String[] args) {
while (true) {
printBoard();
playerMove();
if (checkWin()) {
printBoard();
System.out.println("Player " + currentPlayer + " wins!");
break;
}
if (isBoardFull()) {
printBoard();
System.out.println("It's a draw!");
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
41/62
}
}
}
java
import java.util.Scanner;
42/62
System.out.print("Enter a password: ");
String password = scanner.nextLine();
if (isValidPassword(password)) {
System.out.println("Password is valid.");
} else {
System.out.println("Password must be at least 8 characters long and
contain at least one digit and one uppercase letter.");
}
}
java
import java.util.Scanner;
java
43/62
import java.util.Scanner;
if (isLeapYear(year)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
import java.util.Scanner;
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
44/62
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) return false;
}
return true;
}
}
import java.util.Scanner;
java
import java.util.Scanner;
45/62
System.out.println("Factorial of " + number + " is: " + factorial);
}
import java.util.Calendar;
import java.util.Scanner;
46/62
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 1, 0}
};
if (solveMaze(maze, 0, 0)) {
System.out.println("Path exists in the maze.");
} else {
System.out.println("No path exists in the maze.");
}
}
These additional programs cover various topics and concepts in Java, including algorithms,
data structures, and basic game mechanics. Let me know if you need more programs or
explanations!
continue
Sure! Here are more Java programs that cover different concepts and functionalities:
47/62
52. Palindrome Checker
java
import java.util.Scanner;
import java.util.Arrays;
48/62
if (array1[i] < array2[j]) {
merged[k++] = array1[i++];
} else {
merged[k++] = array2[j++];
}
}
while (i < array1.length) {
merged[k++] = array1[i++];
}
while (j < array2.length) {
merged[k++] = array2[j++];
}
return merged;
}
}
import java.util.Scanner;
49/62
55. Find the Largest Element in an Array
java
import java.util.Scanner;
import java.util.Scanner;
50/62
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String result = removeWhitespaces(str);
System.out.println("String without whitespaces: " + result);
}
import java.util.Arrays;
import java.util.Scanner;
Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
import java.util.Scanner;
51/62
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] questions = {
"What is the capital of France? (a) Paris (b) London (c) Berlin",
"What is 2 + 2? (a) 3 (b) 4 (c) 5"
};
char[] answers = {'a', 'b'};
int score = 0;
import java.util.Scanner;
52/62
60. Simple To-Do List Application
java
import java.util.ArrayList;
import java.util.Scanner;
do {
System.out.println("1. Add Task 2. View Tasks 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter a task: ");
String task = scanner.nextLine();
tasks.add(task);
break;
case 2:
System.out.println("Tasks:");
for (String t : tasks) {
System.out.println(t);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
}
}
53/62
java
import java.util.Scanner;
import java.util.Scanner;
54/62
java
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Scanner;
do {
System.out.println("1. Add Item 2. View Cart 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter item name: ");
55/62
item = scanner.nextLine();
cart.add(item);
break;
case 2:
System.out.println("Items in cart:");
for (String cartItem : cart) {
System.out.println(cartItem);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
}
}
import java.util.Scanner;
if (choice.equalsIgnoreCase("left")) {
System.out.println("You encounter a friendly elf who gives you a
treasure.");
} else if (choice.equalsIgnoreCase("right")) {
System.out.println("You encounter a scary monster and run away!");
} else {
System.out.println("Invalid choice. The game ends.");
}
56/62
}
}
import java.util.ArrayList;
import java.util.Scanner;
do {
System.out.println("1. Add Expense 2. View Expenses 3. Exit");
option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Enter expense amount: ");
expense = scanner.nextDouble();
expenses.add(expense);
break;
case 2:
System.out.println("Expenses:");
for (double e : expenses) {
System.out.println(e);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
57/62
}
}
java
import java.util.HashMap;
import java.util.Scanner;
do {
System.out.print("Enter a URL to shorten (or 'exit' to quit): ");
String url = scanner.nextLine();
if (url.equalsIgnoreCase("exit")) break;
import java.util.Random;
import java.util.Scanner;
58/62
public class GuessingGame {
public static void main(String[] args) {
Random random = new Random();
int numberToGuess = random.nextInt(100) + 1;
int guess;
Scanner scanner = new Scanner(System.in);
do {
guess = scanner.nextInt();
if (guess < numberToGuess) {
System.out.println("Too low! Try again.");
} else if (guess > numberToGuess) {
System.out.println("Too high! Try again.");
} else {
System.out.println("Congratulations! You've guessed the number!");
}
} while (guess != numberToGuess);
}
}
import java.util.Scanner;
public BankAccount() {
this.balance = 0.0;
}
59/62
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient funds.");
}
}
do {
System.out.println("1. Deposit 2. Withdraw 3. Check Balance 4. Exit");
option = scanner.nextInt();
switch (option) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
account.withdraw(withdrawAmount);
break;
case 3:
account.checkBalance();
break;
case 4:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 4);
60/62
}
}
java
import java.util.ArrayList;
import java.util.Scanner;
do {
System.out.println("1. Add Note 2. View Notes 3. Exit");
option = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (option) {
case 1:
System.out.print("Enter note: ");
note = scanner.nextLine();
notes.add(note);
break;
case 2:
System.out.println("Notes:");
for (String n : notes) {
System.out.println(n);
}
break;
case 3:
System.out.println("Exiting.");
break;
default:
System.out.println("Invalid option.");
}
} while (option != 3);
61/62
}
}
These additional programs cover a variety of functionalities and concepts in Java, from basic
data handling to simple applications. Let me know if you need any more programs or specific
topics!
62/62