0% found this document useful (0 votes)
9 views73 pages

Java Program samples

This document contains a lot of sample Java programs which are solved by me.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views73 pages

Java Program samples

This document contains a lot of sample Java programs which are solved by me.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

ST AUGUSTINE'S DAY SCHOOL,

SHYAMNAGAR

NAME: ROUNAK BASAK


Class and Section: 11 A
Roll Number: 31
Subject: Computer Science

Page 1|
ACKNOWLEDGEMENT

I would like to express my sincere gratitude to all those who have


helped me successfully complete this Computer Science project as
part of my Class 11 ISC curriculum.

First and foremost, I thank St. Augustine's Day School,


Shyamnagar and the Council for the Indian School Certificate
Examinations (CISCE) for including this project in the syllabus,
which allowed me to explore programming concepts practically.

I am extremely thankful to my respected Computer Science


teacher, ESHA MA’AM, for their constant support, guidance, and
encouragement throughout the development of this project. Their
expert suggestions and valuable insights helped me understand the
logic and structure behind writing efficient Java programs.

I also wish to thank my parents and friends for their patience,


motivation, and support throughout the course of this work.

This project includes a set of Java programs based on topics


covered in the Class 11 ISC syllabus. These programs were
written, compiled, and tested using a Java development
environment (Blue J).

This experience has greatly enhanced my understanding of


programming logic and has prepared me better for future
challenges in the field of Computer Science.

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.

The programs included in this project cover a wide range of basic


programming concepts such as input/output operations, conditional
statements, loops, functions, and data handling. These programs have
been implemented using the Python programming language (or specify
your language, e.g., C++ or Java), which is widely used in both academic
and professional settings.

Working on these programs has enhanced my logical thinking, improved


my coding skills, and given me hands-on experience in problem-solving
using computers. This project not only reflects my learning journey but
also prepares me for more advanced concepts in computer science in the
coming years.

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

Algorithm to Check Evil Number:


1. Start
2. Input number N (where 2 < N < 100)
3. Convert N to binary
4. Count the number of 1’s in the binary
5. If the count is even, print "EVIL NUMBER"
6. Else, print "NOT AN EVIL NUMBER"
7. End

Page 5|
SOURCE CODE:
import java.util.Scanner;

public class EvilNumberCheck {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input
System.out.print("Enter a number (N > 2 and N < 100): ");
int N = sc.nextInt();

if (N <= 2 || N >= 100) {


System.out.println("Invalid input. N must be greater than 2 and less
than 100.");
return;
}

// Convert to binary
String binary = Integer.toBinaryString(N);

// Count number of 1's


int count = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
}
}

// 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.*;

public class DayNumberToDate {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input
System.out.print("Enter Day Number (1 to 366): ");
int dayNumber = sc.nextInt();

System.out.print("Enter Year (4 digits): ");


int year = sc.nextInt();

System.out.print("Enter N (1 to 100): ");


int n = 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;
}

// Check for leap year


boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

// Days in each month


int[] daysInMonth = isLeap ?
new int[]{31,29,31,30,31,30,31,31,30,31,30,31} :
new int[]{31,28,31,30,31,30,31,31,30,31,30,31};

String[] monthNames = {
"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER",
"DECEMBER"
};

// Convert day number to actual date


int monthIndex = 0, day = dayNumber;
while (day > daysInMonth[monthIndex]) {
day -= daysInMonth[monthIndex];
monthIndex++;
if (monthIndex >= 12) {
System.out.println("Invalid day number for the given year.");
return;
}
}

Page 9|
System.out.println("DATE: " + day + getSuffix(day) + " " + monthNames[monthIndex] + ",
" + year);

// Add N days
dayNumber += n;
int newYear = year;

// Recalculate for the new date


while (true) {
isLeap = (newYear % 4 == 0 && newYear % 100 != 0) || (newYear % 400 == 0);
int yearDays = isLeap ? 366 : 365;
if (dayNumber <= yearDays) break;
dayNumber -= yearDays;
newYear++;
}

// Recalculate month and day


isLeap = (newYear % 4 == 0 && newYear % 100 != 0) || (newYear % 400 == 0);
daysInMonth = isLeap ?
new int[]{31,29,31,30,31,30,31,31,30,31,30,31} :
new int[]{31,28,31,30,31,30,31,31,30,31,30,31};

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);
}

// Helper method to get day suffix like "st", "nd", "th"


static String getSuffix(int day) {
if (day >= 11 && day <= 13) return "TH";
return switch (day % 10) {
case 1 -> "ST";
case 2 -> "ND";
case 3 -> "RD";
default -> "TH";
};
}
}

P a g e 10 |
Variable Description Table
Variable Name Data Type Description

Stores the original day number (1–


dayNumber int 366) entered by the user

Stores the input year in 4-digit format


year int

Stores the number of days to be


n int added to the original date

Stores whether the given year (or


isLeap boolean future year) is a leap year or not

Array storing number of days in each


daysInMonth int[] month (adjusted for leap years)

Array storing the names of the


monthNames String[] months

Index to determine the current month


monthIndex int from the day number

Stores the actual day within a month,


derived from the day number
day int

Stores the adjusted year if the added


days move the date into

newYear int the next year

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

2. Input a number num.

3. Convert the number to a string s to perform rotations.

4. Repeat for the number of digits in num:

o Convert the current string s to an integer rotated.

o Check if rotated is a prime number:

▪ If rotated is not prime, exit and print: "Not a Circular Prime".

o Rotate the string by moving the first character to the end.

5. If all rotations are prime, print: "Circular Prime".

6. End

P a g e 13 |
SOURCE CODE :
import java.util.Scanner;

public class CircularPrimeChecker {

// Method to check if a number is prime


static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}

// Method to check if a number is Circular Prime


static boolean isCircularPrime(int num) {
String s = Integer.toString(num);
int len = s.length();

for (int i = 0; i < len; i++) {

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

Stores the original number entered by the


num int
user.

Used to convert num into a string for


s String
digit rotation.

Stores the number of digits in the string


len int
s.

i int Loop counter used to rotate digits.

Stores the rotated number during each


rotated int
iteration.

sc Scanner Used to take input from the user.

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

Algorithm to Convert Number to Words:


1. Input a number num.
2. If num is 0, print "Zero" and stop.
3. If num is negative, make it positive and store "Minus" for the
final output.
4. Split the number into:
o Crores, Lakhs, Thousands, and Hundreds.
5. Convert each part to words using lookup arrays (units[] and
tens[]).
6. Add place values like "Crore", "Lakh", etc., after each part (if
non-zero).
7. Combine all parts and print the final result.
8. End

P a g e 18 |
SOURCE CODE :
import java.util.Scanner;

public class NumberToWordsFull {

static final String[] units = { "", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten",

"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen",


"Eighteen", "Nineteen" };

static final String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety" };

// Converts numbers < 1000

static String convertLessThanThousand(int num) {

String word = "";

if (num >= 100) {

word += units[num / 100] + " Hundred ";

num %= 100;

if (num > 0) {

if (num < 20) {

word += units[num];

} else {
P a g e 19 |
word += tens[num/10];

if (n> 0) {um % 10

word += " " + units[num % 10];

return word.trim();

// Main convert function

static String convertToWords(int num) {

if (num == 0) return "Zero";

if (num < 0) return "Minus " + convertToWords(-num);

String result = "";

if ((num / 10000000) > 0) {

result += convertLessThanThousand(num / 10000000) + " Crore ";

num %= 10000000;

if ((num / 100000) > 0) {

result += convertLessThanThousand(num / 100000) + " Lakh ";

P a g e 20 |
num %= 100000;

if ((num / 1000) > 0) {

result += convertLessThanThousand(num / 1000) + " Thousand ";

num %= 1000;

if (num > 0) {

result += convertLessThanThousand(num);

return result.trim();

// Main Method

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter an integer (0 - 999999999): ");

int number = sc.nextInt();

if (number < 0 || number > 999999999) {

System.out.println("Number out of supported range!");

} else {

String inWords = convertToWords(number);

System.out.println("In words: " + inWords);

P a g e 21 |
Variable Description Table :
Variable Data
Description / Purpose
Name Type

number int Stores the input number entered by the user.

sc Scanner Scanner object used to take input from the user.

Array storing word representations of numbers from


units String[]
0 to 19.

Array storing word representations of multiples of


tens String[]
ten (20, 30, ..., 90).

A working copy of the original number used for


num int
computation.

result String Final string that holds the number in words.

Temporary string used to build words for each


word String
segment (hundreds, thousands, etc.).

Additional (Used Inside Functions):


Data
Variable Name Description / Purpose
Type

Method to convert the full number


convertToWords() String
into words by breaking it into parts.

Method that converts any number less


convertLessThanThousand() String
than 1000 into its word form.

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)

7. Convert both parts to integers and find their sum.


8. If the sum equals n, then it's a Kaprekar number.
9. Print result and end.

P a g e 24 |
SOURCE CODE:
import java.util.Scanner;

public class KaprekarNumber {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input a number
System.out.print("Enter a number: ");
int num = sc.nextInt();

// Check for Kaprekar number


if (isKaprekar(num)) {
System.out.println(num + " is a Kaprekar number.");
} else {
System.out.println(num + " is NOT a Kaprekar number.");
}

sc.close();
}

// Function to check if a number is Kaprekar


static boolean isKaprekar(int n) {
if (n == 1) return true;

int sq = n * n;
String strSq = Integer.toString(sq);
int d = Integer.toString(n).length();

// Split the square into two parts


int len = strSq.length();
String rightPart = strSq.substring(len - d); // last d digits
String leftPart = (len - d > 0) ? strSq.substring(0, len - d) : "0"; //
remaining left digits

int left = Integer.parse ;

P a g e 25 |
Variable Description Table:

Variable Data
Description
Name Type

The number input by the user to be


n int
checked for Kaprekar property

sq int The square of the number n (n * n)

The string representation of the


strSq String
square sq
Number of digits in the original
d int
number n

Length of the square when


len int converted to a string
(strSq.length())
Substring containing the last d
rightPart String
digits of the square
Substring containing the remaining
leftPart String
digits on the left of the square
Integer value of the left part of the
left int
square

Integer value of the right part of the


right int
square

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.

Algorithm: Denomination Break-up and


Amount in Words
1. Start
2. Input the amount n from the user (must be between 1 and 99999)
3. Validate the input:
o If n <= 0 or n > 99999, display an error and stop
4. Initialize an array denominations[] with the available currency values in
descending order:
[1000, 500, 100, 50, 20, 10, 5, 2, 1]
5. Loop through each denomination d in denominations[]:
o Calculate: count = n / d (integer division)
o If count > 0:
▪ Print: d x count = d * count
▪ Update n = n % d
6. Print total number of notes/coins used
8.Convert the original amount into words using the following logic:
o If number is 1000 or more, convert the thousands part and append "Thousand"
o If number is 100 or more, convert the hundreds part and append "Hundred"
o For the remaining number:
▪ If < 20 → use direct words (e.g. Eleven, Fourteen)
▪ If ≥ 20 → use tens array + units array (e.g. "Forty Three")
7. Display the amount in words
8. End

P a g e 28 |
SOURCE CODE:
import java.util.Scanner;

public class BankDenomination {


// Number to words helper arrays
static final String[] units = {
"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"
};

static final String[] tens = {


"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
};

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

// Input amount (up to 5 digits)


System.out.print("Enter the amount (up to 99999): ₹");
int amount = sc.nextInt();

if (amount <= 0 || amount > 99999) {


System.out.println("Invalid amount. Please enter a value between 1 and 99999.");
return;
}

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;
}
}

System.out.println("\nTotal number of notes/coins used: " + totalNotes);


System.out.println("Amount in words: " + convertToWords(sc.nextInt()));
sc.close();
// Function to convert number to words (up to 99999)
public static String convertToWords(int number) {
if (number == 0) return "Zero";

String words = "";

if (number >= 1000) {


words += convertToWords(number / 1000) + " Thousand ";
number %= 1000;
}
if (number >= 100) {
words += convertToWords(number / 100) + " Hundred ";
number %= 100;
}
if (number > 0) {
if (number < 20) {
words += units[number];
} else {
words += tens[number / 10];
if (number % 10 != 0) {
words += " " + units[number % 10];
}

}
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

Stores the total number of


totalNotes int
notes/coins used in the breakup
Used in the loop to hold each
denom int denomination value from the
array
Stores how many notes/coins of
count int a specific denomination are
used
Array holding number names for
units[] String[] 0–19 for number-to-word
conversion

Array holding tens names like


tens[] String[]
"Twenty", "Thirty", etc.

Used as input to
number int convertToWords() method to
convert amount into words

words String Stores the final amount in 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.

Algorithm: ISBN Code Validator


1. Start
2. Input a 10-character ISBN code from the user.
3. Convert the ISBN code to uppercase to handle 'X'.
4. Check if the length of the code is exactly 10 characters:

If not, display an error and exit.


5. Initialize a variable sum = 0.
6. Repeat for each character in the ISBN code from index 0 to 9:
o If it's the last character (i = 9) and is 'X', treat it as digit =
10.
o Else if the character is a digit, convert it to its numeric
value.
o If it’s not a valid digit or 'X' (for the last digit), print an
error and exit.
o Multiply the digit by its weight (10 - i) and add it to sum.
7. After the loop, check if sum % 11 == 0:
o If yes, print "Valid ISBN code".
o Else, print "Invalid ISBN code".
8. End

P a g e 33 |
SOURCE CODE:
import java.util.Scanner;

public class ISBNValidator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input ISBN code


System.out.print("Enter a 10-digit ISBN code: ");
String isbn = sc.nextLine().toUpperCase(); // Accept 'X' as uppercase

// Validate input length


if (isbn.length() != 10) {
System.out.println("Invalid input. ISBN must be 10 characters long.");
return;
}int sum = 0;
for (int i = 0; i < 10; i++) {
char ch = isbn.charAt(i);
int digit;
// If last character is 'X',
treat it as 10 if (i == 9
&& ch == 'X') {
digit = 10;
} else if (Character.isDigit(ch)) {

digit = Character.getNumericValue(ch);
} else {
System.out.println("Invalid character in ISBN.");
return;
}

// Multiply digit with its weight (10 - i)


sum += digit * (10 - i);
}

// Check if the sum is divisible by 11


if (sum % 11 == 0) {
System.out.println("Valid ISBN code.");
} else {
System.out.println("Invalid ISBN code.");
}

sc.close();
}
}
P a g e 34 |
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Purpose

To take input from the user (ISBN


sc Scanner
number).

Stores the 10-character ISBN


isbn String
input by the user.

Stores the cumulative weighted


sum int sum of ISBN digits used for
validation.

Loop counter used to access each


i int
character of the ISBN.

Holds the character at the current


ch char
index i of the ISBN string.

Numeric value of the current ISBN


digit int character (or 10 if the character is
'X').

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”

Algorithm: Arrange Words by Length


and Alphabetically
1. Start
2. Input a string S from the user (terminated with a full stop).
3. Validate:
o If the last character is not a full stop (.), display an error
and exit.
4. Remove the full stop from the string S.
5. Trim extra spaces and split the sentence into words using one
or more spaces (\\s+).
6. Store the words in an array words[].
7. Sort the array using a custom sorting logic:
o First, sort by descending word length
o If two words have the same length, sort them
alphabetically (case-insensitive)
8. For each word in the sorted list:
o Capitalize the first letter, and make all other letters
lowercase
9. Join the words into a single string, with one space between
them.
10. Append a full stop (.) at the end of the sentence

P a g e 37 |
SOURCE CODE:
import java.util.*;

public class SortWordsByLength {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input the sentence


System.out.print("Enter a sentence ending with a full
stop: ");
String input = sc.nextLine().trim();

// Check if input ends with a full stop


if (!input.endsWith(".")) {
System.out.println("Invalid input. Sentence must
end with a full stop.");
return;
}

// Remove the full stop and trim extra spaces


input = input.substring(0, input.length() - 1).trim();

// Split words (using one or more spaces)


String[] words = input.split("\\s+");

// Sort words using custom comparator


Arrays.sort(words, new Comparator<String>() {
public int compare(String a, String b) {
P a g e 38 |
if (b.length() != a.length()) {

Alphabetically
}
}
});

// Capitalize each word


for (int i = 0; i < words.length; i++) {
words[i] = capitalize(words[i]);
}

// Join the words and add full stop


String result = String.join(" ", words) + ".";

System.out.println("OUTPUT:");
System.out.println(result);

sc.close();
}

// Helper method to capitalize first letter


public static String capitalize(String word) {
if (word.length() == 0) return word;
return word.substring(0, 1).toUpperCase() +
word.substring(1).toLowerCase();
}
}

P a g e 39 |
VARIABLE DESCRIPTION TABLE :
Variable Name Data Type Description

Used to read user input from


sc Scanner
the console

Stores the original input


input String
sentence entered by the user
Array that holds the
individual words from the
words String[]
input sentence (excluding
the full stop)

Stores the final sorted and


result String
formatted sentence

Loop counter used to iterate


i int
over the words array

Helper method to capitalize


capitalize() Method the first letter and lowercase
the rest of each word

Comparator used in custom


sorting of the words based
compare() Method
on length and then
alphabetically

Temporary strings used in


a, b String the custom comparator for
sorting

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

Algorithm: Twin Prime Checker


1. Start
2. Input two integers a and b from the user.
3. Check if a is a prime number:
o If a ≤ 1, it is not prime.

o Else, check if any number from 2 to √a divides a:

▪ If any number divides a, it is not prime.

▪ Otherwise, a is prime.

4. Check if b is a prime number using the same logic as


step 3.
5. Check if both a and b are prime and their absolute
difference is 2:

If both conditions are true, print "Twin Prime".


o Else, print "Not Twin Prime".

6. End
P a g e 42 |
SOURCE CODE:
import java.util.Scanner;

public class TwinPrimeCheck {

// Function to check if a number is prime


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) {
Scanner sc = new Scanner(System.in);

// Input two numbers


System.out.print("Enter first number: ");
int a = sc.nextInt();

System.out.print("Enter second number: ");


int b = sc.nextInt();
// Check if both are prime and difference is 2
if (isPrime(a) && isPrime(b) && Math.abs(a - b) == 2) {
System.out.println("Twin Prime");
} else {
System.out.println("Not Twin Prime");
}

sc.close();
}
}

P a g e 43 |
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Description

Used to read input from the


sc Scanner
user

First number entered by the


a int
user

Second number entered by


b int
the user
Loop counter used in the
i int isPrime() method to check
divisibility

Method that returns true if n


isPrime(int n) boolean is a prime number,
otherwise false

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

Algorithm: Sort Names with Phone Numbers


1. Start
2. Create two arrays:
o names[5] to store names
o phones[5] to store corresponding phone numbers
3. Input 5 names and 5 phone numbers from the user and store them at
corresponding indices.
4. Sort both arrays based on the names in alphabetical order using a sorting
algorithm (e.g. Bubble Sort):
o For each i from 0 to 3:
▪ For each j from 0 to 3 - i:
▪ If names[j] is lexicographically greater than names[j+1]:
▪ Swap names[j] with names[j+1]
▪ Swap corresponding phones[j] with phones[j+1]
5. Display the sorted names along with their corresponding phone numbers.
6. End

P a g e 46 |
SOURCE CODE:
import java.util.Scanner;

public class NamePhoneSort {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = new String[5];
String[] phones = new String[5];

// Input names and phone numbers


System.out.println("Enter 5 names and their phone numbers:");
for (int i = 0; i < 5; i++) {
System.out.print("Name " + (i + 1) + ": ");
names[i] = sc.nextLine();

System.out.print("Phone " + (i + 1) + ": ");


phones[i] = sc.nextLine();
}

// Sort both arrays based on names using Bubble Sort


for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (names[j].compareToIgnoreCase(names[j + 1]) > 0) {
// Swap names
String tempName = names[j];
names[j] = names[j + 1];
names[j + 1] = tempName;

// Swap corresponding phone numbers


String tempPhone = phones[j];
phones[j] = phones[j + 1];
phones[j + 1] = tempPhone;
}
}
}

// Display sorted names with phone numbers


System.out.println("\nSorted Names with Phone Numbers:");
for (int i = 0; i < 5; i++) {
System.out.println(names[i] + " - " + phones[i]);
}

sc.close();
}
}

P a g e 47 |
VARIABLE DESCRIPTION TABLE :

Variable Name Data Type Description

Used to take input from the


sc Scanner
user

Array to store 5 names entered


names String[]
by the user

Array to store 5 phone


phones String[] numbers corresponding to the
names

Loop counters for input and


i, j int
sorting

Temporary variable used to


tempName String swap name values during
sorting

Temporary variable used to


tempPhone String swap phone numbers during
sorting

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;

public class UniqueDigitIntegers {

// Method to check if a number has all unique digits


public static boolean hasUniqueDigits(int num) {
boolean[] digitSeen = new boolean[10]; // For digits 0–9

while (num > 0) {


int digit = num % 10;
if (digitSeen[digit]) {
return false; // Duplicate digit found
}
digitSeen[digit] = true;
num /= 10;
}

return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input the range


System.out.print("Enter lower limit (M): ");
int m = sc.nextInt();

System.out.print("Enter upper limit (N): ");


int n = sc.nextInt();

System.out.println("\nUnique digit integers are:");

int count = 0;

for (int i = m; i <= n; i++) {


if (hasUniqueDigits(i)) {
System.out.print(i + " ");
count++;
}
}

System.out.println("\n\nFrequency of unique digit integers is: " + count);


sc.close();
}
}
P a g e 50 |
VARIABLE DESCRIPTION TABLE:

Variable Name Data Type Description

sc Scanner Used to take input from the user

m int Lower bound of the range

n int Upper bound of the range

Loop counter for checking each


i int
number in the range
Boolean array to track if a digit has
digitSeen[] boolean[]
already occurred
Stores each digit of the number
digit int
during checking
Counts how many numbers have all
count int
unique digits

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.

Algorithm: Paragraph Word Frequency Analyzer


1. Start
2. Input the number of sentences n.
3. Check if n is between 1 and 3:
o If not, display an error message and terminate.
4. Initialize a string paragraph to store the full paragraph.
5. Repeat for each sentence from 1 to n:
o Read the sentence from the user.
o Remove unwanted characters (only allow A–Z, ?, and .).
o Check if the sentence ends with a full stop . or question mark ?
▪ If not, display an error and terminate.
o Append the sentence to paragraph.
6. Clean the paragraph by removing all sentence-ending punctuation (.,
?).
7. Split the cleaned paragraph into words using space as the delimiter.
8. Count the total number of words and print the count.
9. Create a map to store frequency of each word.
10. Iterate through each word:
o If the word exists in the map, increment its count.
o Else, add the word to the map with count = 1.
11. Convert the map into a list of entries and sort them by frequency
(ascending order).
12. Print each word along with its frequency.
13. End.

P a g e 53 |
SOURCE CODE:
import java.util.*;

public class ParagraphProcessor {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Step a: Accept the number of sentences


System.out.print("Enter number of sentences (1 to 3): ");
int n = sc.nextInt();
sc.nextLine(); // consume newline

if (n < 1 || n > 3) {
System.out.println("Error: Number of sentences must be between 1
and 3.");
return;
}

System.out.println("Enter " + n + " sentence(s) in UPPERCASE:");

StringBuilder paragraph = new StringBuilder();

// Input sentences
for (int i = 1; i <= n; i++) {
String line = sc.nextLine().trim();

// Only keep uppercase words and sentence ending punctuation


line = line.replaceAll("[^A-Z ?\\.]", ""); // Remove unwanted
characters

if (!line.endsWith(".") && !line.endsWith("?")) {


System.out.println("Error: Sentence " + i + " must end with '.' or
'?'");
return;

P a g e 54 |
}

// Remove sentence-ending punctuations for word processing


String cleaned = paragraph.toString().replaceAll("[\\.\\?]", "").trim();

// Split into words


String[] words = cleaned.split("\\s+");

// Step b: Count total number of words


System.out.println("\nTotal number of words: " + words.length);

// Step c: Count frequency of each word


Map<String, Integer> freqMap = new HashMap<>();

for (String word : words) {


freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
}

// Sort by frequency (ascending)


List<Map.Entry<String, Integer>> sortedWords = new
ArrayList<>(freqMap.entrySet());

sortedWords.sort(Comparator.comparing(Map.Entry::getValue));

// Display words in ascending order of frequency


System.out.println("\nWords in ascending order of frequency:");
for (Map.Entry<String, Integer> entry : sortedWords) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}

sc.close();
}
}

P a g e 55 |
VARIABLE DESCRIPTION TABLE :

Variable Name Data Type Description

sc Scanner To read user input

n int Number of sentences entered by the user

line String Stores each sentence entered by the user

paragraph StringBuilder Stores the combined paragraph text

cleaned String The paragraph with punctuation removed

words[] String[] Array of individual words from the paragraph

HashMap<String,
freqMap
Integer>
Stores word-frequency pairs

sortedWords List<Map.Entry<>> List used to sort words by frequency

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

public class MatrixProcessor {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input the matrix size M


System.out.print("Enter the order of the matrix (M): ");
int M = sc.nextInt();

if (M <= 3 || M >= 10) {


System.out.println("Error: M must be > 3 and < 10.");
return;
}

int[][] A = new int[M][M];


System.out.println("Enter the elements of the matrix (positive integers):");

// Input matrix
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = sc.nextInt();
}
}

// Store original matrix for later display


int[][] original = new int[M][M];
for (int i = 0; i < M; i++)

P a g e 59 |
original[i] = Arrays.copyOf(A[i], M);

// Step 1: Extract and sort non-boundary elements


List<Integer> innerElements = new ArrayList<>();
for (int i = 1; i < M - 1; i++) {
for (int j = 1; j < M - 1; j++) {
innerElements.add(A[i][j]);
}
}

Collections.sort(innerElements);

// Step 1.2: Put sorted elements back into inner matrix


int idx = 0;
for (int i = 1; i < M - 1; i++) {
for (int j = 1; j < M - 1; j++) {
A[i][j] = innerElements.get(idx++);
}
}

// Step 2: Calculate diagonal sum


int sum = 0;
System.out.println("\nDIAGONAL ELEMENTS");
for (int i = 0; i < M; i++) {
int d1 = A[i][i];
int d2 = A[i][M - 1 - i];
System.out.println(d1 + " " + d2);
sum += d1;
if (i != M - 1 - i) {
sum += d2;
}
}

// Step 3: Display original matrix


System.out.println("\nORIGINAL MATRIX:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
System.out.print(original[i][j] + "\t");
}
System.out.println();
}

// Step 4: Display rearranged matrix


System.out.println("\nREARRANGED MATRIX:");
for (int i = 0; i < M; i++) {
for (int j = 0; j < M; j++) {
System.out.print(A[i][j] + "\t");
}
System.out.println();
}

// Step 5: Display sum of diagonals


System.out.println("\nSUM OF THE DIAGONAL ELEMENTS = " + sum);
}
}

P a g e 60 |
VARIABLE DESCRIPTION TABLE:

Variable Type Description

M int Size of the square matrix (MxM)

A int[][] The working matrix

A copy of the original matrix


original int[][]
before rearranging

i, j int Loop counters

List of all non-boundary elements


innerElements List<Integer>
for sorting

Index to place sorted elements


idx int
back into the matrix

sum int Sum of both diagonals

Elements on the primary and


d1, d2 int
secondary diagonals

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;

public class DigitSumFinder {

// Method to calculate the sum of digits of a number


public static int digitSum(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}

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

Lower bound input


M int
number

N int Target digit sum

Current number being


number int
checked
Sum of digits of the
sum int
current number
Used to take input
sc Scanner
from user

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];
}

// Accepts array elements


void inputarray() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter " + size + " elements:");
for (int i = 0; i < size; i++) {
com[i] = sc.nextInt();
}
}

// Sorts the array using Selection Sort


void sort() {
for (int i = 0; i < size - 1; i++) {
int min = i;
for (int j = i + 1; j < size; j++) {
if (com[j] < com[min]) {
min = j;
}
}
// Swap
int temp = com[i];
com[i] = com[min];
com[min] = temp;
}
}

// Combines two arrays (with duplicates) into current object


void mix(Combine A, Combine B) {
size = A.size + B.size;
com = new int[size];

for (int i = 0; i < A.size; i++) {


com[i] = A.com[i]
P a g e 68 |
}

for (int i = 0; i < B.size; i++) {


com[A.size + i] = B.com[i];
}
}

// Displays the array


void display() {
System.out.println("Array elements:");
for (int i = 0; i < size; i++) {
System.out.print(com[i] + " ");
}
System.out.println();
}

// Main method to test


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input sizes for both arrays


System.out.print("Enter number of elements in first array: ");
int n1 = sc.nextInt();
System.out.print("Enter number of elements in second array: ");
int n2 = sc.nextInt();

Combine A = new Combine(n1);


Combine B = new Combine(n2);

A.inputarray();
B.inputarray();

Combine C = new Combine(n1 + n2); // to store combined array

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

com[] int[] Array to store integers

size int Size of the array

Loop and sorting control


i, j, min int
variables

Temporary variable for


temp int
swapping

Sizes of the first and second


n1, n2 int
arrays

Objects representing the two


A, B, C Combine
input arrays and the result array

sc Scanner For input from user

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 |

You might also like