PROGRAM 1
Question: Write a program to accept a non-negative integer, display its binary equivalent,
count the number of 1's and state whether it is an Evil number (even number of 1's).
Code:
import [Link].*;
class Program1EvilNumber
public static void main(String[] args)
// Program to check if a number is an Evil number
Scanner sc = new Scanner([Link]);
[Link]("Enter a non-negative integer:");
int n = [Link]();
if (n < 0)
[Link]("Only non-negative integers are allowed.");
[Link]();
return;
int original = n;
StringBuilder binary = new StringBuilder();
int onesCount = 0;
if (n == 0)
[Link]('0');
else
while (n > 0)
int bit = n % 2;
if (bit == 1)
{
onesCount++;
[Link](bit);
n = n / 2;
[Link]();
[Link]("Number: " + original);
[Link]("Binary equivalent: " + [Link]());
[Link]("Number of 1's in binary: " + onesCount);
if (onesCount % 2 == 0)
[Link](original + " is an Evil number.");
else
[Link](original + " is NOT an Evil number.");
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Enter a non-negative integer:
9
Number: 9
Binary equivalent: 1001
Number of 1's in binary: 2
9 is an Evil number.
PROGRAM 2
Question: Design a menu-driven program to perform addition, multiplication and transpose
of 2D integer matrices. Validate dimensions before operations.
Code:
import [Link].*;
class Program2MatrixOperations
public static void main(String[] args)
// Menu-driven program for matrix operations
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns for Matrix A:");
int r1 = [Link]();
int c1 = [Link]();
[Link]("Enter rows and columns for Matrix B:");
int r2 = [Link]();
int c2 = [Link]();
int[][] A = new int[r1][c1];
int[][] B = new int[r2][c2];
[Link]("Enter elements of Matrix A:");
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
A[i][j] = [Link]();
[Link]("Enter elements of Matrix B:");
for (int i = 0; i < r2; i++)
for (int j = 0; j < c2; j++)
B[i][j] = [Link]();
}
while (true)
[Link]("\n--- MATRIX MENU ---");
[Link]("1. Add A + B");
[Link]("2. Multiply A x B");
[Link]("3. Transpose A or B");
[Link]("4. Exit");
[Link]("Choose option: ");
int ch = [Link]();
if (ch == 1)
if (r1 != r2 || c1 != c2)
[Link]("Addition not possible: dimensions mismatch.");
else
int[][] sum = new int[r1][c1];
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
sum[i][j] = A[i][j] + B[i][j];
[Link]("Result of A + B:");
printMatrix(sum);
}
else if (ch == 2)
if (c1 != r2)
[Link]("Multiplication not possible: columns of A != rows of
B.");
else
int[][] prod = new int[r1][c2];
for (int i = 0; i < r1; i++)
for (int j = 0; j < c2; j++)
int s = 0;
for (int k = 0; k < c1; k++)
s += A[i][k] * B[k][j];
prod[i][j] = s;
[Link]("Result of A x B:");
printMatrix(prod);
}
else if (ch == 3)
[Link]("Transpose which matrix? (A/B): ");
char which = [Link]().toUpperCase().charAt(0);
if (which == 'A')
[Link]("Transpose of A:");
printMatrix(transpose(A));
else if (which == 'B')
[Link]("Transpose of B:");
printMatrix(transpose(B));
else
[Link]("Invalid choice.");
else if (ch == 4)
[Link]("Exiting menu.");
break;
else
{
[Link]("Invalid option. Try again.");
[Link]();
static void printMatrix(int[][] M)
for (int[] row : M)
for (int v : row)
[Link](v + "\t");
[Link]();
static int[][] transpose(int[][] M)
int r = [Link], c = M[0].length;
int[][] T = new int[c][r];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
T[j][i] = M[i][j];
}
return T;
}
OUTPUT FOR THE GIVEN CODE IS
Result of A + B:\n3 2 \n4 9
PROGRAM 3
Question: Given a list of strings, group anagrams together (use a 1D array of strings) and
display groups.
Code:
import [Link].*;
class Program3GroupAnagrams
public static void main(String[] args)
// Group anagrams from input list
Scanner sc = new Scanner([Link]);
[Link]("Enter number of strings:");
int n = [Link]();
[Link]();
String[] arr = new String[n];
[Link]("Enter the strings (one per line):");
for (int i = 0; i < n; i++)
arr[i] = [Link]();
Map<String, List<String>> groups = new LinkedHashMap<>();
for (String s : arr)
String key = canonical(s);
[Link](key, new ArrayList<String>());
[Link](key).add(s);
[Link]("\nAnagram Groups:");
int groupNo = 1;
for (List<String> g : [Link]())
[Link]("Group " + (groupNo++) + ": ");
[Link]([Link](", ", g));
}
[Link]();
static String canonical(String s)
char[] ch = [Link]("\\s+", "").toLowerCase().toCharArray();
[Link](ch);
return new String(ch);
}
OUTPUT FOR THE GIVEN CODE IS
Anagram Groups:\nGroup 1: eat, tea, ate\nGroup 2: tan, nat
PROGRAM 4
Question: Implement QuickSort on an integer array. Also count and display the number of
element comparisons made during sorting.
Code:
import [Link].*;
class Program4QuickSortCount
static long comparisons = 0;
public static void main(String[] args)
// QuickSort with comparison counter
Scanner sc = new Scanner([Link]);
[Link]("Enter number of elements:");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter elements:");
for (int i = 0; i < n; i++)
arr[i] = [Link]();
comparisons = 0;
quickSort(arr, 0, n - 1);
[Link]("Sorted array:");
for (int v : arr)
[Link](v + " ");
[Link]("\nTotal comparisons during QuickSort: " + comparisons);
[Link]();
static void quickSort(int[] A, int low, int high)
if (low < high)
{
int p = partition(A, low, high);
quickSort(A, low, p - 1);
quickSort(A, p + 1, high);
static int partition(int[] A, int low, int high)
int pivot = A[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++)
comparisons++;
if (A[j] <= pivot)
i++;
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
int tmp = A[i + 1];
A[i + 1] = A[high];
A[high] = tmp;
return i + 1;
}
OUTPUT FOR THE GIVEN CODE IS
Sorted array:\n1 5 7 8 9 10 \nTotal comparisons during QuickSort: 12
PROGRAM 5
Question: Create a small bank system demonstrating inheritance: an Account super class and
SavingsAccount and CurrentAccount subclasses. Include constructors and overridden withdraw
behaviour for overdraft.
Code:
import [Link].*;
class Program5BankSystem
public static void main(String[] args)
// Demonstrates inheritance and constructors
SavingsAccount sacc = new SavingsAccount("A001", 1000.0, 4.0);
[Link](500);
[Link](200);
[Link]();
[Link]("SavingsAccount final balance: " + [Link]());
CurrentAccount cacc = new CurrentAccount("C001", 2000.0, 1000.0);
[Link](2800);
[Link]("CurrentAccount balance after overdraft withdrawal: " +
[Link]());
class Account
protected String accNo;
protected double balance;
public Account(String accNo, double balance)
[Link] = accNo;
[Link] = balance;
public void deposit(double amt)
{
if (amt > 0)
balance += amt;
public boolean withdraw(double amt)
if (amt > 0 && amt <= balance)
balance -= amt;
return true;
return false;
public double getBalance()
return balance;
class SavingsAccount extends Account
private double interestPercent;
public SavingsAccount(String accNo, double balance, double interestPercent)
super(accNo, balance);
[Link] = interestPercent;
}
public void applyInterest()
double interest = balance * interestPercent / 100.0;
balance += interest;
class CurrentAccount extends Account
private double overdraftLimit;
public CurrentAccount(String accNo, double balance, double overdraftLimit)
super(accNo, balance);
[Link] = overdraftLimit;
@Override
public boolean withdraw(double amt)
if (amt <= balance + overdraftLimit)
balance -= amt;
return true;
return false;
}
OUTPUT FOR THE GIVEN CODE IS
SavingsAccount final balance: 1326.0\nCurrentAccount balance after overdraft withdrawal: -800
PROGRAM 6
Question: Write a switch-case driven Student Management program allowing add, display,
search by ID, update marks and grade report. Use arrays or arraylists.
Code:
import [Link].*;
class Program6StudentManagement
public static void main(String[] args)
// Menu-driven student registration and grade management using switch-case
Scanner sc = new Scanner([Link]);
List<Integer> ids = new ArrayList<Integer>();
List<String> names = new ArrayList<String>();
List<Integer> marks = new ArrayList<Integer>();
while (true)
[Link]("\n--- STUDENT MANAGEMENT ---");
[Link]("1. Add Student");
[Link]("2. Display All Students");
[Link]("3. Search Student by ID");
[Link]("4. Update Marks");
[Link]("5. Generate Grade Report");
[Link]("6. Exit");
[Link]("Choose option: ");
int option = [Link]();
switch (option)
case 1:
[Link]("Enter ID: ");
int id = [Link]();
[Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Marks (0-100): ");
int m = [Link]();
[Link](id);
[Link](name);
[Link](m);
[Link]("Student added.");
break;
case 2:
[Link]("All students:");
for (int i = 0; i < [Link](); i++)
[Link]([Link](i) + " | " + [Link](i) + " | " +
[Link](i));
break;
case 3:
[Link]("Enter search ID: ");
int sid = [Link]();
int idx = [Link](sid);
if (idx >= 0)
[Link]("Found: " + [Link](idx) + " | " + [Link](idx) +
" | " + [Link](idx));
else
[Link]("Student not found.");
break;
}
case 4:
[Link]("Enter ID to update marks: ");
int uid = [Link]();
int pos = [Link](uid);
if (pos >= 0)
[Link]("Enter new marks: ");
int nm = [Link]();
[Link](pos, nm);
[Link]("Marks updated.");
else
[Link]("Student not found.");
break;
case 5:
[Link]("Grade Report:");
for (int i = 0; i < [Link](); i++)
[Link]([Link](i) + " : Marks=" + [Link](i) + " =>
Grade = " + grade([Link](i)));
break;
case 6:
{
[Link]("Exiting Student Management.");
[Link]();
return;
default:
[Link]("Invalid option, try again.");
static String grade(int marks)
if (marks >= 90)
return "A+";
if (marks >= 80)
return "A";
if (marks >= 70)
return "B+";
}
if (marks >= 60)
return "B";
if (marks >= 50)
return "C";
return "F";
}
OUTPUT FOR THE GIVEN CODE IS
Alice : Marks=92 => Grade = A+\nBob : Marks=68 => Grade = B
PROGRAM 7
Question: Write a program to check whether a given number is a Smith number. (Sum of
digits equals sum of digits of its prime factors.)
Code:
import [Link].*;
class Program7SmithNumber
public static void main(String[] args)
// Smith number checker
Scanner sc = new Scanner([Link]);
[Link]("Enter a number:");
int n = [Link]();
int original = n;
int sod = sumDigits(n);
int sopf = 0; // sum of digits of prime factors
int temp = n;
for (int i = 2; i <= temp && n > 1; i++)
while (n % i == 0)
sopf += sumDigits(i);
n /= i;
if (sod == sopf && original > 1)
[Link](original + " is a Smith number.");
else
{
[Link](original + " is NOT a Smith number.");
[Link]();
static int sumDigits(int x)
int s = 0;
while (x > 0)
s += x % 10;
x /= 10;
return s;
}
OUTPUT FOR THE GIVEN CODE IS
Input: 94\nOutput: SMITH Number
PROGRAM 8
Question: Accept a positive integer and print its prime factorization (list of prime
factors). Store factors in an array and display them.
Code:
import [Link].*;
class Program8PrimeFactors
public static void main(String[] args)
// Prime factorization storing factors in a list
Scanner sc = new Scanner([Link]);
[Link]("Enter a positive integer:");
int n = [Link]();
int num = n;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= num && n > 1; i++)
while (n % i == 0)
[Link](i);
n /= i;
[Link]("Prime factors of " + num + " are: " + factors);
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Enter a positive integer:\n84\nPrime factors of 84 are: [2, 2, 3, 7]
PROGRAM 9
Question: Represent a sparse matrix using 3-tuple representation (row, column, value).
Convert a given 2D matrix into its sparse representation and display.
Code:
import [Link].*;
class Program9SparseMatrix
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter rows and columns:");
int r = [Link]();
int c = [Link]();
int[][] M = new int[r][c];
[Link]("Enter matrix values row-wise:");
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
M[i][j] = [Link]();
List<int[]> tuples = new ArrayList<int[]>();
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
if (M[i][j] != 0)
[Link](new int[]
{
i, j, M[i][j]
}
);
[Link]("Sparse 3-tuple representation (row, col, val):");
for (int[] t : tuples)
[Link]([Link](t));
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Sparse 3-tuple representation (row, col, val):\n[0, 1, 5]\n[1, 0, 3]
PROGRAM 10
Question: Implement a stack ADT using an array. Provide push, pop, peek, display, and
underflow/overflow handling. Demonstrate with a small menu.
Code:
import [Link].*;
class Program10ArrayStack
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter stack capacity: ");
int cap = [Link]();
ArrayStack st = new ArrayStack(cap);
while (true)
[Link]("\[Link] [Link] [Link] [Link] [Link]");
int ch = [Link]();
if (ch == 1)
[Link]("Enter value to push: ");
int v = [Link]();
[Link](v);
else if (ch == 2)
Integer popped = [Link]();
if (popped == null)
[Link]("Underflow - stack is empty.");
else
{
[Link]("Popped: " + popped);
else if (ch == 3)
Integer top = [Link]();
if (top == null)
[Link]("Stack empty.");
else
[Link]("Top: " + top);
else if (ch == 4)
[Link]();
else
[Link]("Exiting.");
break;
}
[Link]();
class ArrayStack
private int[] arr;
private int top;
public ArrayStack(int capacity)
arr = new int[capacity];
top = -1;
public void push(int x)
if (top == [Link] - 1)
[Link]("Overflow - cannot push.");
return;
arr[++top] = x;
public Integer pop()
if (top == -1)
return null;
}
return arr[top--];
public Integer peek()
if (top == -1) return null;
return arr[top];
public void display()
if (top == -1)
[Link]("Stack empty.");
return;
for (int i = top; i >= 0; i--)
[Link](arr[i]);
}
OUTPUT FOR THE GIVEN CODE IS
Enter stack capacity: 3\nPush 10, Push 20, Display:\n20\n10
PROGRAM 11
Question: Write a program to check password strength: check length, presence of uppercase,
lowercase, digit and special character, and give a strength rating.
Code:
import [Link].*;
class Program11PasswordStrength
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter password to check:");
String pwd = [Link]();
int score = 0;
if ([Link]() >= 8) score++;
if ([Link](".*[A-Z].*")) score++;
if ([Link](".*[a-z].*")) score++;
if ([Link](".*\\d.*")) score++;
if ([Link](".*[^a-zA-Z0-9].*")) score++;
String strength;
if (score <= 2) strength = "Weak";
else if (score == 3) strength = "Moderate";
else if (score == 4) strength = "Strong";
else strength = "Very Strong";
[Link]("Password strength: " + strength);
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Enter password to check:\nAbc@1234\nPassword strength: Very Strong
PROGRAM 12
Question: Implement binary search (iterative and recursive) on a sorted integer array and
display the index if found or a message if not.
Code:
import [Link].*;
class Program12BinarySearch
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter sorted array size:");
int n = [Link]();
int[] arr = new int[n];
[Link]("Enter sorted elements:");
for (int i = 0; i < n; i++) arr[i] = [Link]();
[Link]("Enter key to search:");
int key = [Link]();
int idxIter = binarySearchIter(arr, key);
int idxRec = binarySearchRec(arr, 0, n - 1, key);
[Link]("Iterative result index: " + idxIter);
[Link]("Recursive result index: " + idxRec);
[Link]();
static int binarySearchIter(int[] A, int key)
int lo = 0, hi = [Link] - 1;
while (lo <= hi)
int mid = lo + (hi - lo) / 2;
if (A[mid] == key) return mid;
else if (A[mid] < key) lo = mid + 1;
else hi = mid - 1;
return -1;
}
static int binarySearchRec(int[] A, int lo, int hi, int key)
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (A[mid] == key) return mid;
if (A[mid] < key) return binarySearchRec(A, mid + 1, hi, key);
return binarySearchRec(A, lo, mid - 1, key);
}
OUTPUT FOR THE GIVEN CODE IS
Iterative result index: 2\nRecursive result index: 2
PROGRAM 13
Question: Create a simple phonebook using TreeMap to store name->number pairs. Support
add, search by name, delete and display all entries sorted by name.
Code:
import [Link].*;
class Program13PhoneBook
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
TreeMap<String, String> phone = new TreeMap<String, String>();
[Link]("Alice", "9876543210");
[Link]("Bob", "9123456780");
while (true)
[Link]("\[Link] [Link] [Link] [Link] All [Link]");
int ch = [Link]();
[Link]();
if (ch == 1)
[Link]("Name: ");
String name = [Link]();
[Link]("Number: ");
String num = [Link]();
[Link](name, num);
else if (ch == 2)
[Link]("Search name: ");
String name = [Link]();
String num = [Link](name);
if (num == null) [Link]("Not found.");
else [Link](name + " -> " + num);
else if (ch == 3)
{
[Link]("Delete name: ");
String name = [Link]();
[Link](name);
else if (ch == 4)
for ([Link]<String, String> e : [Link]())
[Link]([Link]() + " : " + [Link]());
else break;
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Alice : 9876543210\nBob : 9123456780
PROGRAM 14
Question: Write a program to encrypt and decrypt text using Caesar cipher with a user-
specified shift. Maintain case and ignore non-letters.
Code:
import [Link].*;
class Program14CaesarCipher
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter text:");
String text = [Link]();
[Link]("Enter shift (positive for encrypt):");
int shift = [Link]();
[Link]("Encrypted: " + encrypt(text, shift));
[Link]("Decrypted: " + encrypt(text, 26 - (shift % 26)));
[Link]();
static String encrypt(String s, int k)
StringBuilder sb = new StringBuilder();
for (char ch : [Link]())
if ([Link](ch))
[Link]((char)('A' + (ch - 'A' + k) % 26));
else if ([Link](ch))
[Link]((char)('a' + (ch - 'a' + k) % 26));
}
else
[Link](ch);
return [Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Enter text:\nHello World\nEnter shift:\n3\nEncrypted: Khoor Zruog\nDecrypted: Hello World
PROGRAM 15
Question: Given a set of intervals (start,end) in an array, merge overlapping intervals
and output the merged list.
Code:
import [Link].*;
class Program15MergeIntervals
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter number of intervals:");
int n = [Link]();
int[][] intervals = new int[n][2];
[Link]("Enter intervals as start end each line:");
for (int i = 0; i < n; i++)
intervals[i][0] = [Link]();
intervals[i][1] = [Link]();
List<int[]> merged = merge(intervals);
[Link]("Merged intervals:");
for (int[] iv : merged)
[Link](iv[0] + " " + iv[1]);
[Link]();
static List<int[]> merge(int[][] intervals)
if ([Link] == 0) return new ArrayList<int[]>();
[Link](intervals, new Comparator<int[]>()
{
public int compare(int[] a, int[] b)
return [Link](a[0], b[0]);
}
);
List<int[]> res = new ArrayList<int[]>();
int[] cur = intervals[0];
for (int i = 1; i < [Link]; i++)
if (intervals[i][0] <= cur[1])
cur[1] = [Link](cur[1], intervals[i][1]);
else
[Link](cur);
cur = intervals[i];
[Link](cur);
return res;
}
OUTPUT FOR THE GIVEN CODE IS
Input intervals: [1 3],[2 6],[8 10]\nMerged intervals:\n1 6\n8 10
PROGRAM 16
Question: Create a base class User with constructors and a subclass Admin. Build a small
menu that requires password authentication to access admin operations.
Code:
import [Link].*;
class Program16AuthMenu
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
User u = new User("guest");
Admin a = new Admin("admin", "secret123");
[Link]("Enter username: ");
String name = [Link]();
[Link]("Enter password: ");
String pwd = [Link]();
if ([Link](name, pwd))
[Link]();
else
[Link]("Authentication failed. Limited access granted.");
[Link]();
[Link]();
class User
protected String username;
public User(String username)
[Link] = username;
public void showMenu()
[Link]("User menu: View only.");
class Admin extends User
private String password;
public Admin(String username, String password)
super(username);
[Link] = password;
public boolean authenticate(String name, String pwd)
return [Link](name) && [Link](pwd);
public void showMenu()
[Link]("Admin menu: Add/Remove users, View logs.");
}
OUTPUT FOR THE GIVEN CODE IS
Enter username: admin\nEnter password: secret123\nAdmin menu: Add/Remove users, View lo
PROGRAM 17
Question: Accept a postfix (Reverse Polish) expression and evaluate it using a stack.
Support + - * / and integer operands.
Code:
import [Link].*;
class Program17PostfixEval
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter space-separated postfix expression (e.g. 2 3 + 4 *):");
String line = [Link]();
String[] tokens = [Link]("\\s+");
Stack<Integer> st = new Stack<Integer>();
for (String t : tokens)
if ([Link]("-?\\d+"))
[Link]([Link](t));
else
int b = [Link]();
int a = [Link]();
int r = 0;
switch (t)
case "+":
r = a + b;
break;
}
case "-":
r = a - b;
break;
case "*":
r = a * b;
break;
case "/":
r = a / b;
break;
[Link](r);
[Link]("Result: " + [Link]());
[Link]();
}
OUTPUT FOR THE GIVEN CODE IS
Input: 2 3 + 4 *\nResult: 20
PROGRAM 18
Question: Write a program to compute GCD and LCM of two positive integers using Euclid's
algorithm. Display steps optionally.
Code:
import [Link].*;
class Program18GcdLcm
public static void main(String[] args)
Scanner sc = new Scanner([Link]);
[Link]("Enter two positive integers:");
int a = [Link]();
int b = [Link]();
int g = gcd(a, b);
long l = (long)a / g * b;
[Link]("GCD: " + g);
[Link]("LCM: " + l);
[Link]();
static int gcd(int x, int y)
while (y != 0)
int t = x % y;
x = y;
y = t;
return x;
}
OUTPUT FOR THE GIVEN CODE IS
Enter two positive integers:\n12 18\nGCD: 6\nLCM: 36