Java Program samples
Java Program samples
SHYAMNAGAR
Page 1|
ACKNOWLEDGEMENT
Page 2|
INDEX
PAGE
SERIAL NUMBER PROGRAM DESCRIPTION
NUMBER
1 INDEX 3
2 EVIL NUMBER 4
3 DAY NUMBER TO DATE 7
4 CIRCULAR PRIME CHECKER 12
5 NUMBER TO WORDS FULL 17
6 KAPREKAR 23
7 BANK DENOMINATION 27
8 ISBN VALIDATOR 32
9 SORT WORD BY LENGTH 36
10 TWIN PRIME CHECK 41
11 NAME PHONE SORT 45
12 UNIQUE DIGIT INTEGERS 48
13 PARAGRAPH PROCESSOR 52
14 MATRIX PROCESSOR 57
15 DIGIT SUM FINDER 63
16 COMBINE 66
17 CONCLUSION 70
18 BIBLIOGRAPHY 71
Page 3|
Introduction
This computer project is a part of my Class 11 Science Stream curriculum
and includes a set of 15 programs based on the topics covered during the
academic year. The aim of this project is to apply the concepts learned in
theory to practical programming tasks, thereby strengthening my
understanding of the subject.
Page 4|
Question 1:
An Evil number is a positive whole number which has even number of 1’s in its binary
equivalent.
Example: Binary equivalent of 9 is 1001, which contains even number of 1’s.
Thus, 9 is an Evil Number.
A few Evil numbers are 3, 5, 6, 9....
Design a program to accept a positive whole number ‘N’ where N>2 and N<100. Find the
binary equivalent of the number and count the number of 1s in it and display whether it is an
Evil number or not with an appropriate message.
Test your program with the following data and some random data:
INPUT: N = 15
BINARY EQUIVALENT: 1111
NUMBER OF 1’s: 4
OUTPUT: EVIL NUMBER
Page 5|
SOURCE CODE:
import java.util.Scanner;
// Input
System.out.print("Enter a number (N > 2 and N < 100): ");
int N = sc.nextInt();
// Convert to binary
String binary = Integer.toBinaryString(N);
// Output
System.out.println("Binary Equivalent: " + binary);
System.out.println("Number of 1’s: " + count);
if (count % 2 == 0) {
System.out.println("OUTPUT: EVIL NUMBER");
} else {
System.out.println("OUTPUT: NOT AN EVIL NUMBER");
}
}
Page 6|
Variable Description Table:
Variable
DataType Description
Name
n int Stores the input number entered by the user
binary String Stores the binary equivalent of the number n
countOnes int Stores the count of 1’s in the binary number
Loop control variable used to iterate over each digit of the binary
i int
string
SAMPLE OUTPUTS :
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
Page 7|
QUESTION 2:
Design a program to accept a number (between 1 and 366), year(in 4 digits) generate and
display the corresponding date. Also accept 'N '(1<=N<=100) from the user to compute
and display the future date corresponding to 'N' days after the generated date. Display an
error message If the value of the day number, year and N are not within the limit or not
according to the condition specified. Test your program with the following data and some
random data: Example 1: INPUT: DAY NUMBER: 255 YEAR: 2018 DATE AFTER (N
DAYS); 22 OUTPUT: DATE: 12 TH SEPTEMBER, 2018 DATE AFTER 22 DAYS 4TH
OCTOBER, 2018
ALGORITHM:
1. Start
2. Input dayNumber, year, and N
3. Check if inputs are within valid range
4. Convert dayNumber to a date (day + month)
5. Display the date
6. Add N days to dayNumber, adjust year if needed
7. Convert new day number to date and display it
8. End
Page 8|
SOURCE CODE :
import java.util.*;
// Input
System.out.print("Enter Day Number (1 to 366): ");
int dayNumber = sc.nextInt();
// Validate input
if (dayNumber < 1 || dayNumber > 366 || year < 1000 || year > 9999 || n < 1 || n > 100) {
System.out.println("Invalid input! Please follow the specified limits.");
return;
}
String[] monthNames = {
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER",
"DECEMBER"
};
Page 9|
System.out.println("DATE: " + day + getSuffix(day) + " " + monthNames[monthIndex] + ",
" + year);
// Add N days
dayNumber += n;
int newYear = year;
monthIndex = 0;
day = dayNumber;
while (day > daysInMonth[monthIndex]) {
day -= daysInMonth[monthIndex];
monthIndex++;
}
System.out.println("DATE AFTER " + n + " DAYS: " + day + getSuffix(day) + " " +
monthNames[monthIndex] + ", " + newYear);
}
P a g e 10 |
Variable Description Table
Variable Name Data Type Description
P a g e 11 |
SAMPLE OUTPUTS :
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 12 |
QUESTION 3:
A Circular Prime is a prime number that remains prime under cyclic shifts of its digits. When the
leftmost digit is removed and replaced at the end of the remaining string of digits, the generated
number is still prime. The process is repeated until the original number is reached again. A number
is said to be prime if it has only two factors 1 and itself.
Example:
131
311
113
Hence, 131 is a circular prime.
Accept a positive number N and check whether it is a circular prime or not. The new numbers
formed after the shifting of the digits should also be displayed. Test your program with the
following data and some random data:
Example
INPUT: N = 197
OUTPUT: 197 971 719 197 IS A CIRCULAR PRIME.
Algorithm :
1. Start
6. End
P a g e 13 |
SOURCE CODE :
import java.util.Scanner;
P a g e 14 |
int rotated =
Integer.parseInt(s); if
(!isPrime(rotated)) return false;
s = s.substring(1) + s.charAt(0); // Rotate digits
}
return true;
}
// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to check if it's a Circular
Prime: ");
int number = sc.nextInt();
if (isCircularPrime(number)) {
System.out.println(number + " is a Circular Prime.");
} else {
System.out.println(number + " is NOT a Circular Prime.");
}
}
}
P a g e 15 |
Variable Description Table
Variable Data
Purpose / Description
Name Type
P a g e 16 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 17 |
QUESTION 4:
WAP in java to input a number and print it in words.
Example:
INPUT:
143
OUTPUT:
One Hundred Forty Three
P a g e 18 |
SOURCE CODE :
import java.util.Scanner;
static final String[] units = { "", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten",
static final String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety" };
num %= 100;
if (num > 0) {
word += units[num];
} else {
P a g e 19 |
word += tens[num/10];
if (n> 0) {um % 10
return word.trim();
num %= 10000000;
P a g e 20 |
num %= 100000;
num %= 1000;
if (num > 0) {
result += convertLessThanThousand(num);
return result.trim();
// Main Method
} else {
P a g e 21 |
Variable Description Table :
Variable Data
Description / Purpose
Name Type
P a g e 22 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
OUTPUT 4:
P a g e 23 |
QUESTION 5:
Write a Program in Java to input a number and check whether it is a Kaprekar number or not.
Note: A positive whole number ‘n’ that has ‘d’ number of digits is squared and split into two
pieces, a right-hand piece that has ‘d’ digits and a left-hand piece that has remaining ‘d’ or
‘d1’ digits. If the sum of the two pieces is equal to the number, then ‘n’ is a Kaprekar number.
The first few Kaprekar numbers are: 9, 45, 297…
Example 45 452 = 2025,
right-hand piece of 2025 = 25
and left-hand piece of 2025 = 20 Sum = 25 + 20 = 45,
i.e., equal to the number. Hence, 45 is a Kaprekar number.
Algorithm :
1. Start
2. Input a number n.
3. If n == 1, then print "n is a Kaprekar number" and
exit.
4. Square the number → sq = n × n
5. Convert sq and n to strings to get their digit lengths.
6. Split sq into:
o Right part = last d digits (where d is number of
digits in n)
o Left part = remaining digits (use "0" if empty)
P a g e 24 |
SOURCE CODE:
import java.util.Scanner;
// Input a number
System.out.print("Enter a number: ");
int num = sc.nextInt();
sc.close();
}
int sq = n * n;
String strSq = Integer.toString(sq);
int d = Integer.toString(n).length();
P a g e 25 |
Variable Description Table:
Variable Data
Description
Name Type
P a g e 26 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 27 |
QUESTION 6:
A bank intends to design a program to display the denomination of an input amount, upto 5
digits. The available denomination with the bank are of rupees 1000,500, 100, 50, 20, 10, 5, 2
and 1. Design a program to accept the amount from the user and display the break-up in
descending order of denominations. ( i, e preference should be given to the highest
denomination available) along with the total number of notes. [Note: only the denomination
used should be displayed]. Also print the amount in words according to the digits.
P a g e 28 |
SOURCE CODE:
import java.util.Scanner;
P a g e 29 |
// Denominations available
int[] denominations = {1000, 500, 100, 50, 20, 10, 5, 2, 1};
int totalNotes = 0;
System.out.println("\nDenomination break-up:");
for (int denom : denominations) {
int count = amount / denom;
if (count > 0) {
System.out.println("₹" + denom + " x " + count + " = ₹" + (denom * count));
totalNotes += count;
amount %= denom;
}
}
}
return words.trim();
}
P a g e 30 |
Variable
Description Table:
Variable Name Data Type Description
sc Scanner Used to take input from the user
Stores the input amount entered
amount int
by the user
Array containing available
denominations int[] denominations in descending
order
Used as input to
number int convertToWords() method to
convert amount into words
P a g e 31 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
P a g e 32 |
QUESTION 7:
An ISBN (International Standard Book Number) is a ten digit code which uniquely
identifies a book. The first nine digits represent the Group, Publisher and Title of the
book and the last digit is used to check whether ISBN is correct or not. Each of the
first nine digits of the code can take a value between 0 and 9. Sometimes it is
necessary to make the last digit equal to ten; this is done by writing the last digit of
the code as X. To verify an ISBN, calculate 10 times the first digit, plus 9 times the
second digit, plus 8 times the third and so on until we add 1 time the last digit. If the
final number leaves no remainder when divided by 11, the code is a valid ISBN.
P a g e 33 |
SOURCE CODE:
import java.util.Scanner;
digit = Character.getNumericValue(ch);
} else {
System.out.println("Invalid character in ISBN.");
return;
}
sc.close();
}
}
P a g e 34 |
VARIABLE DESCRIPTION TABLE:
P a g e 35 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
P a g e 36 |
QUESTION 8:
Write a program which takes a string (maximum 80 characters) terminated by a full stop the words
in this string are assumed to be separated by one or more blanks. Arrange the words of the input
string in descending order of their lengths. Same length words should be sorted alphabetically. Each
word must start with an uppercase letter and the sentence should be terminated by a full stop.
Sample Data:
INPUT: “This is human resource department”
OUTPUT: “Department Human Resource This Is”
P a g e 37 |
SOURCE CODE:
import java.util.*;
Alphabetically
}
}
});
System.out.println("OUTPUT:");
System.out.println(result);
sc.close();
}
P a g e 39 |
VARIABLE DESCRIPTION TABLE :
Variable Name Data Type Description
P a g e 40 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 41 |
QUESTION 9:
WAP in java to check is a pair of a numbers are twin prime or not.
Example 1:
INPUT:
3
5
OUTPUT:
Twin Prime
Example 2:
INPUT:
3
7
OUTPUT
Not Twin Prime
▪ Otherwise, a is prime.
6. End
P a g e 42 |
SOURCE CODE:
import java.util.Scanner;
sc.close();
}
}
P a g e 43 |
VARIABLE DESCRIPTION TABLE:
P a g e 44 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 45 |
QUESTION 10:
Write a program in java to accept 5 names and 5 phone numbers in two different arrays and
display the names with their respective phone numbers in alphabetical order.
Example:
INPUT:
Array 1:
JOHN
AMELIA
KRISTEN
LEWIS
ZAC
Array 2:
9856721856
7842357169
9865715972
8642689726
8775534278
OUTPUT:
NAME PHONE NUMBER
AMELIA 7842357169
JOHN 9856721856
KRISTEN 9865715972
LEWIS 8642689726
ZAC 8775534278
P a g e 46 |
SOURCE CODE:
import java.util.Scanner;
sc.close();
}
}
P a g e 47 |
VARIABLE DESCRIPTION TABLE :
SAMPLE OUTPUT:
P a g e 48 |
QUESTION 11:
A unique digit integer is a positive integer (without leading 0's) with no duplicate digits(for
e.g. ,7,135,214) whereas 33, 3121 and 300 are not.
Given, negative integers M and M, WAP in java to determine how many unique digit integers
are there in the range between m and n and output them.
The input contains 2 positive int. M and N. Assume m<30,000 and n<30,000. You are to
output the no. of unique digit integers in the specified range along with their values in the
format Specified below
INPUT:
M =100
N=120
Algorithm
1. Start
2. Input two integers M and N such that M < N and both < 30000
3. Initialize a variable count = 0
4. Loop from i = M to N:
o Call function hasUniqueDigits(i):
▪ Use a boolean array digitSeen[10] to mark seen digits
▪ Extract digits of i one by one using modulus and division
▪ If any digit repeats, return false
▪ Else return true
o If the number has all unique digits:
▪ Print the number
▪ Increment count
5. After the loop, display the frequency of unique digit numbers
6. End
P a g e 49 |
SOURCE CODE :
import java.util.Scanner;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
P a g e 51 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 52 |
QUESTION 12:
. Input a paragraph containing 'n' number of sentences where (1 < = n < 4). The words are to be
separated with a single blank space and are in UPPERCASE. A sentence may be terminated
either with a full stop '.' Or a question mark '?' only. Any other character may be ignored.
Perform the following operations:
a. Accept the number of sentences. If the number of sentences exceeds the limit,
an appropriateerror message must be displayed.
b. Find the number of words in the whole paragraph.
c. Display the words in ascending order of their frequency. Words with same
frequency mayappear in any order.
P a g e 53 |
SOURCE CODE:
import java.util.*;
if (n < 1 || n > 3) {
System.out.println("Error: Number of sentences must be between 1
and 3.");
return;
}
// Input sentences
for (int i = 1; i <= n; i++) {
String line = sc.nextLine().trim();
P a g e 54 |
}
sortedWords.sort(Comparator.comparing(Map.Entry::getValue));
sc.close();
}
}
P a g e 55 |
VARIABLE DESCRIPTION TABLE :
HashMap<String,
freqMap
Integer>
Stores word-frequency pairs
Map.Entry<String,
entry Represents a key-value pair in the map
Integer>
P a g e 56 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 57 |
QUESTION 13:
Write a program to declare a square matrix A[][] of order (M × M) where 'M' must be greater
than 3 and less than 10. Allow the user to input positive integers into this matrix.
Perform the following tasks on the matrix:
1. Sort the non-boundary elements in ascending order using any standard sorting technique
and rearrange them in the matrix.
2. Calculate the sum of both the diagonals.
3. Display the original matrix, rearranged matrix and only the diagonal elements of the
rearranged matrix with their sum.
Test your program for the following data and some random data:
Example 1
INPUT:
M=4
9215
8 13 8 4
15 6 3 11
7 12 23 8
OUTPUT:
ORIGINAL MATRIX
9215
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
9215
8364
15 8 13 11
7 12 23 8
DIAGONAL ELEMENTS
95
36
8 13
78
SUM OF THE DIAGONAL ELEMENTS = 5
P a g e 58 |
Algorithm:
1. Start
2. Accept the matrix order M.
3. If M <= 3 or M >= 10, print error and stop.
4. Create an M×M matrix A and input all elements.
5. Copy original matrix A to original for display.
6. Extract non-boundary elements into a list.
7. Sort the list in ascending order.
8. Place sorted values back into the non-boundary positions of matrix A.
9. Calculate the sum of both diagonals:
o Primary diagonal: A[i][i]
o Secondary diagonal: A[i][M - 1 - i]
o Avoid adding the center element twice if it overlaps
10. Display:
o Original matrix
o Rearranged matrix
o Diagonal elements
o Diagonal sum
11. End
SOURCE CODE:
import java.util.*;
// Input matrix
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = sc.nextInt();
}
}
P a g e 59 |
original[i] = Arrays.copyOf(A[i], M);
Collections.sort(innerElements);
P a g e 60 |
VARIABLE DESCRIPTION TABLE:
P a g e 61 |
SAMPLE OUTPUTS:
OUTPUT 1:
P a g e 62 |
OUTPUT 2:
P a g e 63 |
QUESTION 14:
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less
than 100.
Find the smallest integer that is greater than M and whose digits add up to N.
For example, if M =100 and N = 11, then the smallest integer greater than 100 whose digits add
up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest required
number whose sum of the digits is equal to N. Also, print the total number of digits present in the
required number. The program should check for the validity of the inputs and display an
appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1
Input:
M = 100
N = 11
Output:
The required number = 119
Total number of digits = 3
Algorithm
1. Start
2. Input two integers: M and N.
3. Check for valid input:
o M should be > 100 and < 10000
o N should be > 0 and < 100
4. If invalid, print an error message and stop.
5. Initialize a variable number = M + 1.
6. Loop from number upward:
o Calculate sum of digits of number
o If digit sum equals N, break the loop
7. Print:
o The required number
o Total number of digits in the number
8. End
P a g e 64 |
SOURCE CODE:
import java.util.Scanner;
// Main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input
System.out.print("Enter M (100 < M < 10000): ");
int M = sc.nextInt();
System.out.print("Enter N (N < 100): ");
int N = sc.nextInt();
// Input validation
if (M <= 100 || M >= 10000 || N <= 0 || N >= 100) {
System.out.println("Invalid input. M must be between 100 and 10000 and N must
be less than 100.");
return;
}
// Find the smallest number greater than M whose digit sum is N
int number = M + 1;
while (true) {
if (digitSum(number) == N) {
System.out.println("The required number = " + number);
System.out.println("Total number of digits = " +
String.valueOf(number).length());
break;
}
number++;
}
sc.close();
}
}
P a g e 65 |
VARIABLE DESCRIPTION TABLE :
Variable Type Description
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
P a g e 66 |
QUESTION 15:
. A class Combine contains an array of integers which combines two arrays into a single array
including the duplicate elements, if any, and sorts the combined array.
Some of the members of the class are given below:
Class name : Combine
Data Members/instance variables:
com [] : integer array
size : size of the array
Member functions/methods:
Combine (int nn) : parameterized constructor to assign size = nn
void inputarray() : accepts the array elements.
void sort () : sorts the elements of the combined array in ascending order using the
selection sort technique.
void mix (Combine A, Combine B): combines the parameterized object arrays and stores the result
in the current object array along with duplicate elements, if any.
void display (): displays the array elements
Specify the class Combine giving details of the constructor (int), void inputarray(),
void sort (), void mix (Combine, Combine) and void display ().
Also, define the main () function to create an object and call the methods accordingly to enable
the task.
Algorithm:
1. Start
2. Input sizes n1 and n2 for two arrays.
3. Create two Combine objects A and B with sizes n1 and
n2.
4. Input elements for both arrays using inputarray().
5. Create a third Combine object C of size n1 + n2.
6. Use C.mix(A, B) to combine both arrays into C.
7. Display combined array before sorting.
8. Use C.sort() to sort the combined array using selection
sort.
9. Display the sorted array.
10. End
P a g e 67 |
SOURCE CODE:
import java.util.Scanner;
class Combine {
int[] com;
int size;
// Parameterized constructor
Combine(int nn) {
size = nn;
com = new int[size];
}
A.inputarray();
B.inputarray();
C.mix(A, B);
System.out.println("\nCombined Array before Sorting:");
C.display();
C.sort();
System.out.println("\nCombined Array after Sorting:");
C.display();
}
}
P a g e 69 |
VARIABLE DESCRIPTION TABLE :
Variable Name Type Description
P a g e 70 |
SAMPLE OUTPUTS:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
P a g e 71 |
CONCLUSION :
In this series of Java programs, I explored the application of
object-oriented programming to solve real-world problems
involving arrays. Specifically, I developed the Combine class,
which demonstrated how to effectively manage multiple arrays
by combining, sorting, and displaying their contents.
The use of selection sort provided a clear understanding of basic
sorting algorithms, while combining arrays helped reinforce
concepts like constructors, method interactions, and data
encapsulation.
Through various test cases, the program successfully handled
inputs of different sizes and contents, including duplicates, and
produced correct, sorted results. This practical implementation
enhanced our understanding of arrays, sorting logic, and class-
based design in Java.
P a g e 72 |
BIBLIOGRAPHY:
▪ Herbert Schildt, Java: The Complete Reference,
McGraw Hill Education, 11th Edition
• Used for understanding Java syntax, OOP concepts, and
standard library usage.
▪ Oracle Java Documentation,
https://docs.oracle.com/javase/
• Official documentation referenced for method descriptions,
array handling, and Scanner class usage.
▪ GeeksforGeeks, https://www.geeksforgeeks.org/
• Referred to for selection sort algorithm explanation and
examples.
▪ W3Schools Java Tutorial,
https://www.w3schools.com/java/
• Used for syntax refreshers and input/output handling in Java.
▪ TutorialsPoint Java Guide,
https://www.tutorialspoint.com/java/index.htm
• Consulted for class creation, constructors, and user- defined
methods in Java.
P a g e 73 |