Professional Documents
Culture Documents
Name :
Class : 12
Section: A
Roll number :
Java Programs
1. Addition of two binary numbers
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
Question:
Write a Java program to find out the longest word in a sentence using recursion.
Working Algorithm:
Java Code:
import java.util.Scanner;
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
scanner.close();
Enter a sentence:
Java is an object oriented programming language
The longest word is: programming
3. Printing lucky numbers in a given range
Question:
Write a Java program to print all the lucky numbers in a given range.
Working Algorithm:
Java Code:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
Question:
Write a Java program to compute the saddle point of a matrix. A saddle point is an element
which is
smallest in its row and largest in its column.
Working Algorithm:
Java Code:
import java.util.Scanner;
findSaddlePoint(matrix);
}
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
if (month == 2) {
return isLeapYear(year) ? day <= 29 : day <= 28;
}
if (month == 4 || month == 6 || month == 9 || month == 11)
{ return day <= 30;
}
return true;
}
}
Enter day:
29
Enter month:
2
Enter year:
2001
The date is invalid.
Question:
Write a Java program to sort the words of a sentence in ascending order using recursion.
Working Algorithm:
Java Code:
import java.util.Scanner;
public static void merge(String[] words, int left, int mid, int right)
{ int n1 = mid - left + 1;
int n2 = right - mid;
String[] L = new
String[n1];
String[] R = new String[n2];
for (int i = 0; i < n1; i++) {
L[i] = words[left + i];
}
for (int j = 0; j < n2; j++)
{ R[j] = words[mid + 1 +
j];
}
int i = 0, j = 0;
int k = left;
while (i < n1 && j < n2) {
if (L[i].compareTo(R[j]) <= 0) {
words[k] = L[i];
i++;
} else {
words[k] = R[j];
j++;
} k+
+;
}
while (i < n1)
{ words[k] = L[i];
i++;
k++;
}
while (j < n2)
{ words[k] =
R[j]; j++;
k++;
}
}
}
Enter a sentence:
this is a sample sentence
Sorted sentence:
a is sample sentence this
Question:
Write a Java program to compute the HCF (Highest Common Factor) and LCM (Least
Common Multiple)
of two numbers using recursion.
Working Algorithm:
Java Code:
import java.util.Scanner;
Question:
Write a Java program to find the day of the week corresponding to a given date.
Working Algorithm:
Java Code:
import java.util.Scanner;
switch (dayOfWeek) {
case 0:
return "Saturday";
case 1:
return "Sunday";
case 2:
return "Monday";
case 3:
return "Tuesday";
case 4:
return "Wednesday";
case 5:
return "Thursday";
case 6:
return "Friday";
default:
return "Invalid";
}
}
}
Enter day:
15
Enter month (1 for January, 12 for December):
8
Enter year:
2023
The day of the week is: Sunday
Question:
Write a Java program to compute the date after adding a certain number of days to a given
date.
Working Algorithm:
1. Input day, month, and year of the initial date from the user.
2. Input the number of days to be added.
3. Iteratively add days, updating month and year as required.
4. Display the resulting date.
Java Code:
import java.util.Scanner;
public static int[] findDateAfterDays(int day, int month, int year, int daysToAdd)
{ int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year))
{ daysInMonth[2] =
29;
}
day += daysToAdd;
while (day > daysInMonth[month]) {
day -= daysInMonth[month];
month++;
if (month > 12) {
month = 1;
year++;
if (isLeapYear(year))
{ daysInMonth[2] = 29;
} else {
daysInMonth[2] = 28;
}
}
}
return new int[]{day, month, year};
}
Enter day:
25
Enter month (1 for January, 12 for December):
8
Enter year:
2023
Enter the number of days to add:
40
The date after adding the days is: 4/10/2023
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
import java.util.Arrays;
public class BoundarySort {
sortBoundary(matrix);
System.out.println("Matrix after boundary sorting:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
{ System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
Question:
Working Algorithm:
Java Code:
Stack(int size) {
MAX = size;
arr = new int[MAX];
top = -1;
}
boolean isFull() {
return top == MAX - 1;
}
boolean isEmpty() {
return top == -1;
}
void push(int x) {
if (isFull()) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = x;
System.out.println(x + " pushed to stack");
}
int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top--];
}
int peek() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top];
}
}
1 pushed to stack
2 pushed to stack
3 pushed to stack
Top element: 3
3 popped from stack
Top element: 2
Question:
Working Algorithm:
Java Code:
Queue(int size) {
MAX = size;
arr = new int[MAX];
front = 0;
rear = -1;
size = 0;
}
boolean isFull()
{ return size ==
MAX;
}
boolean isEmpty() {
return size == 0;
}
void enqueue(int x) {
if (isFull()) {
System.out.println("Queue Overflow");
return;
}
rear = (rear + 1) % MAX;
arr[rear] = x;
size++;
System.out.println(x + " enqueued to queue");
}
int dequeue() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
int item = arr[front];
front = (front + 1) % MAX;
size--;
return item;
}
int peek() {
if (isEmpty()) {
System.out.println("Queue Underflow");
return -1;
}
return arr[front];
}
}
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
Front element: 10
10 dequeued from queue
Front element: 20
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
import java.math.BigInteger;
Question:
Write a Java program to implement a singly linked list. The program should have operations
for inserting at the beginning, inserting at the end, deleting from the beginning, deleting
from the end, and displaying the list.
Working Algorithm:
class Node
{ int data;
Node next;
class LinkedList {
Node head;
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Insert at beginning");
System.out.println("2. Insert at end");
System.out.println("3. Delete from beginning");
System.out.println("4. Delete from end");
System.out.println("5. Display");
System.out.println("6. Exit");
System.out.println("Enter your choice:");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter value to insert:");
int value1 = scanner.nextInt();
list.insertAtBeginning(value1);
break;
case 2:
System.out.println("Enter value to insert:");
int value2 = scanner.nextInt();
list.insertAtEnd(value2);
break;
case 3:
list.deleteFromBeginning();
break;
case 4:
list.deleteFromEnd();
break;
case 5:
list.display();
break;
case 6:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice!");
}
} while (choice != 6);
scanner.close();
}
}
Menu:
1. Insert at beginning
2. Insert at end
3. Delete from beginning
4. Delete from end
5. Display
6. Exit
Enter your choice:
1
Enter value to insert:
10
Menu:
...
1. Insert at beginning
...
5. Display
6. Exit
Enter your choice:
5
10 -> null
...
6. Exit
Enter your choice:
6
Exiting...
Question:
Write a Java program to swap the values of two numbers without using a third variable.
Working Algorithm:
Java Code:
import java.util.Scanner;
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping:");
System.out.println("First number: " + a);
System.out.println("Second number: " + b);
}
}
Question:
Write a Java program to generate the Pascal triangle pattern for a given number of rows.
Working Algorithm:
Question:
Write a Java program to implement a circular queue using an array. The program should
have operations for enqueuing, dequeuing, and displaying the elements of the queue.
Working Algorithm:
Java Code:
import java.util.Scanner;
class CircularQueue {
private int[] queue;
private int front;
private int rear;
private int size;
while (true) {
System.out.println("\nEnter an option:\n1. Enqueue\n2. Dequeue\n3. Display\n4.
Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the value to enqueue:");
int value = scanner.nextInt();
queue.enqueue(value);
break;
case 2:
queue.dequeue();
break;
case 3:
queue.display();
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid option! Try again.");
}
}
}
}
Question:
Write a Java program to generate a magic square for an odd-sized matrix. A magic square is
a matrix in which the sums of the numbers in each row, each column, and both main
diagonals are the same.
Working Algorithm:
Java Code:
import java.util.Scanner;
if (n % 2 == 0) {
System.out.println("Size should be an odd number.");
return;
}
System.out.println("Magic Square:");
for (int i = 0; i < n; i++)
{ for (int j = 0; j < n; j++)
{
System.out.print(magicSquare[i][j] + "\t");
}
System.out.println();
}
}
if (magicSquare[nextRow][nextCol] == 0) {
i = nextRow;
j = nextCol;
} else {
i = (i + 1) % n;
}
}
return magicSquare;
}
}
Question:
Write a Java program to convert a decimal number to its representation in a given base
(between 2 and 16).
Working Algorithm:
import java.util.Scanner;
import java.util.Stack;
System.out.println("Number " + decimalNumber + " in base " + base + " is: " +
convertedNumber);
}
return result.toString();
}
}
Question:
Write a Java program to calculate the distance between two points in the X-Y plane. The
program should use objects to represent points and pass them to a method to compute the
distance.
Working Algorithm:
Java Code:
import java.util.Scanner;
class Point {
double x, y;
Question:
Write a Java program to compute the distance between two points in the X-Y plane. Define a
class "Point" with members x and y. Pass objects of the Point class to a function to compute
the distance.
Working Algorithm:
Java Code:
import java.util.Scanner;
class Point {
double x, y;
Point(double x, double y) {
this.x = x;
this.y = y;
}
double distance(Point p) {
return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2));
}
}
Question:
Write a Java program to create a text file and write user-input content to it.
Working Algorithm:
Java Code:
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
try {
FileWriter fileWriter = new FileWriter(filename);
fileWriter.write(content);
fileWriter.close();
System.out.println("File " + filename + " has been created successfully!");
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}
}
Question:
Write a Java program to create a text file and write user input to that file until the user
enters "exit".
Working Algorithm:
1. Use the FileWriter and BufferedWriter classes to create and write to a text file.
2. Take input from the user using the Scanner class.
3. Write each line of input to the file until the user enters "exit".
4. Close the BufferedWriter and FileWriter objects.
5. Display a message indicating that the file has been created successfully.
Java Code:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
Question:
Write a Java program that simulates a bank system. Create a base class "Account" and derive
two subclasses "SavingsAccount" and "CurrentAccount" from it. Implement methods to
deposit, withdraw, and display balance in each account type.
Working Algorithm:
1. Create a class "Account" with attributes for account number and balance.
2. Implement methods for depositing, withdrawing, and displaying the balance.
3. Derive "SavingsAccount" and "CurrentAccount" subclasses from "Account".
4. In the main method, create objects of both account types and perform operations
on them.
Java Code:
class Account {
String accountNumber;
double balance;
Question:
Write a Java program to arrange a given array of numbers in a pendulum fashion. The
smallest element should be in the center, the next larger to its left, the next larger to its
right, and so on.
Working Algorithm:
import java.util.Arrays;
import java.util.Scanner;
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
System.out.println("Pendulum arrangement:");
for (int num : pendulumArr)
{ System.out.print(num + " ");
}
}
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
generatePermutations(str, "");
}
Enter a string:
abc
Permutations:
abc
acb
bac
bca
cab
cba
Question:
Write a Java program to demonstrate the in-order, pre-order, and post-order traversal of a
binary tree.
Working Algorithm:
1. Define a class "Node" with attributes for the value and left and right child nodes.
2. Define methods for in-order, pre-order, and post-order traversal.
3. In the main method, create a sample binary tree and call the traversal methods to
display the results.
Java Code:
class Node
{ int value;
Node left, right;
Node root;
System.out.println("Inorder traversal:");
tree.inorder(tree.root);
System.out.println("\nPreorder traversal:");
tree.preorder(tree.root);
System.out.println("\nPostorder traversal:");
tree.postorder(tree.root);
}
}
Inorder traversal:
42513
Preorder traversal:
12453
Postorder traversal:
45231
Question:
Write a Java program to check whether a given string is a palindrome or not. A palindrome
is a word, phrase, number, or other sequences of characters that reads the same forward
and backward (ignoring spaces, punctuation, and capitalization).
Working Algorithm:
1. Input a string.
2. Convert the string to lowercase and remove non-alphanumeric characters.
3. Compare the modified string with its reverse.
4. If they are the same, the string is a palindrome.
5. Display whether the string is a palindrome or not.
Java Code:
import java.util.Scanner;
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string:");
String str = scanner.nextLine();
scanner.close();
if (isPalindrome(str)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
Enter a string:
A man, a plan, a canal, Panama!
The string is a palindrome.
25. Finding Armstrong numbers
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
if (isArmstrong(num)) {
System.out.println(num + " is an Armstrong number.");
} else {
System.out.println(num + " is not an Armstrong number.");
}
}
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, n);
num /= 10;
}
Enter a number:
153
153 is an Armstrong number.
Question:
Working Algorithm:
Java Code:
import java.util.Scanner;
Enter a number:
5
Factorial of 5 is: 120
Question:
Working Algorithm:
Java Code: