Roll No:- 320 Name: Singh Roshan
[Link] your full name at run time using command line arguments
and display on screen using java program.
Code:- public class
CommandLineName {
public static void main(String[] args) { if
([Link] == 0) {
[Link]("Please provide your full name as command-line arguments.");
return;
}
// Join all arguments to form the full name
String fullName = [Link](" ", args);
[Link]("Your full name is: " + fullName);
}
}
Output:-
[Link] a java program to display result according to given marks by
using if…else if statement.
Code:- import
[Link];
public class StudentResult { public static
void main(String[] args) {
Scanner scanner = new Scanner([Link]);
ACC, MIBM & DICA, Sabargam 1
Roll No:- 320 Name: Singh Roshan
// Taking input from the user
[Link]("Enter your marks: "); int
marks = [Link]();
// Checking result based on marks
if (marks >= 90) {
[Link]("Grade: A+ (Excellent)");
} else if (marks >= 80) {
[Link]("Grade: A (Very Good)");
} else if (marks >= 70) {
[Link]("Grade: B (Good)");
} else if (marks >= 60) {
[Link]("Grade: C (Satisfactory)");
} else if (marks >= 50) {
[Link]("Grade: D (Pass)");
} else {
[Link]("Grade: F (Fail)");
}
[Link]();
}
}
ACC, MIBM & DICA, Sabargam 2
Roll No:- 320 Name: Singh Roshan
Output:-
3. Display factorial of given number using do...while loop in java program.
Code:- import [Link]; public class FactorialDoWhile { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Taking input from the user
[Link]("Enter a number: "); int num
= [Link]();
long factorial = 1; // Variable to store factorial
int i = num; // Counter for loop
// Using do...while loop to calculate factorial
do {
factorial *= i;
i--;
} while (i > 0);
[Link]("Factorial of " + num + " is: " + factorial); [Link]();
}
}
ACC, MIBM & DICA, Sabargam 3
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] swich case statement in java program for printing week name for given
number. Code:-
import [Link];
public class WeekDaySwitch {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Taking input from the user
[Link]("Enter a number (1-7): "); int day
= [Link]();
// Using switch case to determine the weekday
switch (day) {
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
ACC, MIBM & DICA, Sabargam 4
Roll No:- 320 Name: Singh Roshan
break;
case 4:
[Link]("Wednesday");
break;
case 5:
[Link]("Thursday");
break;
case 6:
[Link]("Friday");
break;
case 7:
[Link]("Saturday");
break;
default:
[Link]("Invalid input! Please enter a number between 1 and 7.");
}
[Link]();
}
}
Output:-
[Link] a java program to print following pattern.
ACC, MIBM & DICA, Sabargam 5
Roll No:- 320 Name: Singh Roshan
Code:- public class NumberPattern {
public static void main(String[] args) {
// Outer loop for rows
for (int i = 1; i <= 4; i++) {
// Inner loop for printing numbers in each row
for (int j = 1; j <= i; j++) {
[Link](j);
}
[Link](); // Move to the next line
}
}
}
Output:-
6. Write a java program to print following pattern.
Code:- public class NumberPattern {
public static void main(String[] args) { int
rows = 5; // Number of rows in the pattern
// Outer loop for rows for (int i
= 1; i <= rows; i++) { // Printing
spaces before numbers
for (int j = 1; j <= rows - i; j++) {
[Link](" ");
ACC, MIBM & DICA, Sabargam 6
Roll No:- 320 Name: Singh Roshan
// Printing numbers
for (int j = 1; j <= i; j++) {
[Link](j + " ");
}
[Link](); // Move to the next line
}
}
}
Output:-
7. Write a java program to print following pattern.
Code:- public class NumberPattern {
public static void main(String[] args) { int
rows = 5; // Number of rows in the pattern
// Outer loop for rows for (int i
= 1; i <= rows; i++) { // Printing
spaces before numbers
for (int j = 1; j <= rows - i; j++) {
[Link](" ");
}
// Printing pattern (Numbers and 'A')
ACC, MIBM & DICA, Sabargam 7
Roll No:- 320 Name: Singh Roshan
int num = 1; for (int j = 1; j <= i; j++)
{ [Link](num);
if (j < i) { // Print 'A' between numbers
[Link]("A");
}
num += 2; // Increase number by 2 (odd numbers)
}
[Link](); // Move to the next line
}
}
}
Output:-
8. Write a java program to print following pattern.
Code:- public class NumberPattern {
public static void main(String[] args) { int
rows = 4; // Number of rows in the pattern
// Outer loop for rows for (int i
= 1; i <= rows; i++) { // Printing
spaces before numbers
for (int j = 1; j <= rows - i; j++) {
[Link](" ");
}
ACC, MIBM & DICA, Sabargam 8
Roll No:- 320 Name: Singh Roshan
// Printing descending numbers
for (int j = i; j >= 1; j--) {
[Link](j);
}
// Printing ascending numbers (excluding first digit)
for (int j = 2; j <= i; j++) {
[Link](j);
}
[Link](); // Move to the next line
}
}
}
Output:-
[Link] a program to generate first 10 numbers of fibonacci series.
Code:- public class NumberPattern {
public static void main(String[] args) { int n = 10; // Number
of Fibonacci numbers to generate int first = 0, second = 1; //
First two numbers in the series
[Link]("First " + n + " numbers of Fibonacci series:");
for (int i = 1; i <= n; i++) {
[Link](first + " "); // Print the current number
// Compute the next Fibonacci number
ACC, MIBM & DICA, Sabargam 9
Roll No:- 320 Name: Singh Roshan
int next = first + second;
first = second; second = next;
}
}
}
Output:-
[Link] a class Purchase in which
product_id,product_name,unit_price,total_qty,total_price are data
[Link] Input from user and display.(Use static variable and static
function concept) Code:-
import [Link];
class Purchase { // Data
members
int product_id;
String product_name; double
unit_price; int total_qty;
double total_price;
// Method to take input from the user
void inputDetails() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Product ID: "); product_id
= [Link](); [Link](); //
Consume newline [Link]("Enter Product
Name: "); product_name = [Link]();
ACC, MIBM & DICA, Sabargam 10
Roll No:- 320 Name: Singh Roshan
[Link]("Enter Unit Price: ");
unit_price = [Link]();
[Link]("Enter Total Quantity: ");
total_qty = [Link](); // Calculate total
price total_price = unit_price * total_qty;
[Link]();
// Method to display details void
displayDetails() {
[Link]("\nProduct Details:");
[Link]("Product ID: " + product_id); [Link]("Product
Name: " + product_name);
[Link]("Unit Price: $" + unit_price);
[Link]("Total Quantity: " + total_qty);
[Link]("Total Price: $" + total_price);
}
public static void main(String[] args) {
Purchase purchase = new Purchase(); // Creating object
[Link](); // Taking input [Link](); //
Displaying details
}
}
ACC, MIBM & DICA, Sabargam 11
Roll No:- 320 Name: Singh Roshan
Output:-
11. Make CALC class with two data members no1 and [Link] class have
addition,subtraction,multiplication and divison methods which take input
from user and display result.(Make menu-driven program) Code:-
import [Link].*;
class CALC { // Data
members private double no1,
no2;
// Method to take input from the user public
void inputNumbers() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number: "); no1
= [Link]();
[Link]("Enter second number: "); no2
= [Link]();
// Method for addition public
void addition() {
[Link]("Result: " + (no1 + no2));
}
ACC, MIBM & DICA, Sabargam 12
Roll No:- 320 Name: Singh Roshan
// Method for subtraction public
void subtraction() {
[Link]("Result: " + (no1 - no2));
}
// Method for multiplication public
void multiplication() {
[Link]("Result: " + (no1 * no2));
}
// Method for division public
void division() {
if (no2 != 0) {
[Link]("Result: " + (no1 / no2));
} else {
[Link]("Error: Division by zero is not allowed.");
}
}
}
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
CALC calc = new CALC(); // Creating an object of CALC class
int choice;
do {
// Display menu
[Link]("\n----- MENU -----");
[Link]("1. Addition");
ACC, MIBM & DICA, Sabargam 13
Roll No:- 320 Name: Singh Roshan
[Link]("2. Subtraction");
[Link]("3. Multiplication");
[Link]("4. Division");
[Link]("5. Exit");
[Link]("Enter your choice: "); choice = [Link]();
if (choice >= 1 && choice <= 4) {
[Link](); // Take input only if the operation is chosen
}
// Perform operations based on user choice
switch (choice) {
case 1:
[Link](); break;
case 2:
[Link](); break;
case 3:
[Link]();
break; case 4:
[Link](); break;
case 5:
[Link]("Exiting the program...");
break;
default:
[Link]("Invalid choice! Please enter a number between 1 and 5.");
}
} while (choice != 5);
[Link]();
}
}
ACC, MIBM & DICA, Sabargam 14
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a class Area to calculate and display area of square,rectangle and
triangle using the three same name methods.(Use function overloading
concept) Code:-
import [Link].*;
class Area {
// Method to calculate the area of a square public
void calculate(double side) {
[Link]("Area of Square: " + (side * side));
}
// Method to calculate the area of a rectangle public
void calculate(double length, double breadth) {
[Link]("Area of Rectangle: " + (length * breadth));
}
// Method to calculate the area of a triangle public void calculate(double
base, double height, boolean isTriangle) {
if (isTriangle) {
[Link]("Area of Triangle: " + (0.5 * base * height));
}
}
ACC, MIBM & DICA, Sabargam 15
Roll No:- 320 Name: Singh Roshan
}
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
Area area = new Area();
// Input and calculate area of Square
[Link]("Enter side of square: "); double side
= [Link](); [Link](side); //
Input and calculate area of Rectangle
[Link]("Enter length of rectangle: "); double
length = [Link]();
[Link]("Enter breadth of rectangle: "); double
breadth = [Link](); [Link](length,
breadth);
// Input and calculate area of Triangle
[Link]("Enter base of triangle: "); double
base = [Link]();
[Link]("Enter height of triangle: ");
double height = [Link]();
[Link](base, height, true); [Link]();
}
}
ACC, MIBM & DICA, Sabargam 16
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] STACK class of perform push and pop operations on int array.(Make
menu-driven program) Code:-
import [Link].*;
class STACK {
private int[] stack;
private int top; private int
size;
// Constructor to initialize stack public
STACK(int size) {
[Link] = size;
stack = new int[size]; top
= -1;
// Method to push an element onto the stack public
void push(int value) {
if (top == size - 1) {
[Link]("Stack Overflow! Cannot push " + value);
} else {
stack[++top] = value;
ACC, MIBM & DICA, Sabargam 17
Roll No:- 320 Name: Singh Roshan
[Link](value + " pushed onto the stack.");
}
}
// Method to pop an element from the stack
public void pop() {
if (top == -1) {
[Link]("Stack Underflow! No elements to pop.");
} else {
[Link](stack[top] + " popped from the stack.");
top--;
}
}
// Method to display the stack public
void display() {
if (top == -1) {
[Link]("Stack is empty.");
} else {
[Link]("Stack elements: ");
for (int i = 0; i <= top; i++) {
[Link](stack[i] + " ");
}
[Link]();
}
}
}
ACC, MIBM & DICA, Sabargam 18
Roll No:- 320 Name: Singh Roshan
public class Purchase { public static
void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter stack size: "); int size
= [Link]();
STACK stack = new STACK(size); // Create stack object
int choice;
do {
// Display menu
[Link]("\n----- MENU -----");
[Link]("1. Push");
[Link]("2. Pop");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]("Enter value to push: "); int
value = [Link]();
[Link](value);
break; case
2:
[Link]();
ACC, MIBM & DICA, Sabargam 19
Roll No:- 320 Name: Singh Roshan
break; case
3:
[Link]();
break;
case 4:
[Link]("Exiting the program...");
break;
default:
[Link]("Invalid choice! Please enter a number between 1 and 4.");
}
} while (choice != 4);
[Link]();
}
}
Output:-
ACC, MIBM & DICA, Sabargam 20
Roll No:- 320 Name: Singh Roshan
[Link] a program in java to find a * b where a is a matrix of 3*3 and b is a
matrix of 3*4 .Take the values in matrix a and matrix b from the user.(Use two
dimensional array) Code:-
import [Link].*;
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Define matrices int[][] A = new int[3][3]; //
3x3 matrix int[][] B = new int[3][4]; // 3x4 matrix
int[][] C = new int[3][4]; // Resultant matrix (3x4)
// Input for Matrix A (3x3)
[Link]("Enter elements of 3x3 matrix A:");
for (int i = 0; i < 3; i++) { for
(int j = 0; j < 3; j++) {
A[i][j] = [Link]();
}
}
// Input for Matrix B (3x4)
[Link]("Enter elements of 3x4 matrix B:");
for (int i = 0; i < 3; i++) { for
(int j = 0; j < 4; j++) {
B[i][j] = [Link]();
}
}
ACC, MIBM & DICA, Sabargam 21
Roll No:- 320 Name: Singh Roshan
// Matrix Multiplication: C = A * B
for (int i = 0; i < 3; i++) { for (int j =
0; j < 4; j++) {
C[i][j] = 0; // Initialize result cell for
(int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Display Resultant Matrix C (3x4)
[Link]("\nResultant Matrix C (3x4) after multiplication:");
for (int i = 0; i < 3; i++) { for
(int j = 0; j < 4; j++) {
[Link](C[i][j] + "\t");
}
[Link]();
}
[Link]();
}
}
ACC, MIBM & DICA, Sabargam 22
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a java program to sort a string. Code:-
import [Link].*;
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Take input from the user
[Link]("Enter a string: ");
String input = [Link]();
// Convert string to character array
char[] charArray = [Link]();
// Sort the character array
[Link](charArray);
// Convert back to string
String sortedString = new String(charArray);
// Display the sorted string
ACC, MIBM & DICA, Sabargam 23
Roll No:- 320 Name: Singh Roshan
[Link]("Sorted String: " + sortedString);
[Link]();
}
}
Output:-
[Link] a java program to show use of final keyword before variable,method
and class.
Code:-
// Final class - cannot be inherited final class
FinalClass {
// Final variable - cannot be changed after initialization
final int MAX_VALUE = 100;
// Final method - cannot be overridden in a subclass
public final void display() {
[Link]("This is a final method in a final class.");
}
}
// Class to demonstrate final method behavior (Cannot inherit FinalClass) class
DemoFinal {
// Attempting to override a final method would cause an error
// public void display() { [Link]("Trying to override!"); } //
// Error
void show() {
ACC, MIBM & DICA, Sabargam 24
Roll No:- 320 Name: Singh Roshan
[Link]("This class cannot inherit FinalClass but can use final methods.");
}
}
public class Purchase { public static void
main(String[] args) {
FinalClass obj = new FinalClass();
[Link]("Final variable value: " + obj.MAX_VALUE);
// Attempting to change final variable would cause an error
// obj.MAX_VALUE = 200; // Error
// Calling final method [Link]();
// Demonstrating final class behavior
DemoFinal demo = new DemoFinal(); [Link]();
}
}
Output:-
[Link] a java program to show that super keyword used in child class to
access parent class constructor,data members and member functions. Code:-
class Parent { int num = 100; // Parent class
data member
// Parent class constructor
Parent() {
ACC, MIBM & DICA, Sabargam 25
Roll No:- 320 Name: Singh Roshan
[Link]("Parent class constructor called.");
}
// Parent class method
void display() {
[Link]("This is the parent class method.");
}
}
class Child extends Parent { int num =
200; // Child class data member
// Child class constructor Child() {
super(); // Calls the parent class constructor
[Link]("Child class constructor called.");
}
// Method to demonstrate use of super keyword
void show() {
[Link]("Child class num: " + num);
[Link]("Parent class num using super: " + [Link]); // Access parent data
member
[Link](); // Call parent class method
}
}
public class Purchase { public static void
main(String[] args) {
Child obj = new Child(); // Create an object of the child class
[Link](); // Call method to demonstrate super keyword usage
ACC, MIBM & DICA, Sabargam 26
Roll No:- 320 Name: Singh Roshan
}
}
Output:-
[Link] a java program to show that abstract class can have abstract and
non-abstract(concreate) methods. And child class of abstract class must have
to give definition of all abstract methods of abstract class overwise child class
have to declare abstract class.
Code:-
// Abstract class abstract class
Animal {
// Abstract method (must be implemented in child class) abstract
void sound();
// Concrete (non-abstract) method
void sleep() {
[Link]("Animal is sleeping...");
}
}
// Child class providing definition for all abstract methods class
Dog extends Animal { // Implementing abstract
method
void sound() {
[Link]("Dog barks: Woof Woof!");
}
ACC, MIBM & DICA, Sabargam 27
Roll No:- 320 Name: Singh Roshan
// If a child class does not implement all abstract methods, it must also be
// abstract abstract class Bird extends
Animal {
// Not providing implementation for sound(), so Bird class must be abstract
void fly() {
[Link]("Bird is flying...");
}
}
public class Purchase { public static void
main(String[] args) {
Dog myDog = new Dog(); // Creating an object of Dog [Link]();
// Calls overridden method [Link]();
// Calls inherited concrete method
}
}
Output:-
[Link] a java program which show the dynamic method dispatch(run time
polymorphism) using one parent interface and two child classes. Code:-
interface Animal { void sound();
// Abstract method
}
ACC, MIBM & DICA, Sabargam 28
Roll No:- 320 Name: Singh Roshan
// First child class implementing the interface class Dog
implements Animal {
public void sound() {
[Link]("Dog barks: Woof Woof!");
}
}
// Second child class implementing the interface class
Cat implements Animal {
public void sound() {
[Link]("Cat meows: Meow Meow!");
}
}
public class Purchase { public static void
main(String[] args) {
Animal myAnimal;
// Assign Dog object to Animal reference
myAnimal = new Dog(); [Link]();
// Calls Dog's sound() method
// Assign Cat object to Animal reference myAnimal
= new Cat(); [Link]();
}
}
ACC, MIBM & DICA, Sabargam 29
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a program to accept 5 names from the user(entered names may be
in capital letters or small letters or mix of capital and small.),find and print
those names whose surname is “Patel” (“Patel” can be in capital letters or
small letters pr mix of capital and small). Code:- import [Link];
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
String[] names = new String[5];
// Taking 5 names as input
[Link]("Enter 5 full names (First Name + Surname):");
for (int i = 0; i < 5; i++) {
[Link]("Enter name " + (i + 1) + ": "); names[i] =
[Link]().trim(); // Trim to remove extra spaces
[Link]("\nNames with surname 'Patel':"); for
(String name : names) {
// Split the name to extract surname
String[] parts = [Link]("\\s+"); // Split by spaces
if ([Link] > 1) { // Ensure there's a surname
String surname = parts[[Link] - 1]; // Last part as surname if
([Link]("Patel")) { // Case insensitive check
[Link](name);
}
ACC, MIBM & DICA, Sabargam 30
Roll No:- 320 Name: Singh Roshan
}
}
[Link]();
}
}
Output:-
[Link] a java applications which accept two strings. Merge both the string
using alternate characters of each string. Code:- import [Link];
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Accept two strings from the user
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();
// Merge strings using alternate characters
String mergedString = mergeAlternately(str1, str2);
ACC, MIBM & DICA, Sabargam 31
Roll No:- 320 Name: Singh Roshan
// Display the merged string
[Link]("Merged String: " + mergedString);
[Link]();
}
public static String mergeAlternately(String str1, String str2) {
StringBuilder merged = new StringBuilder(); int len1 = [Link](),
len2 = [Link](); int minLen =
[Link](len1, len2);
// Merge alternate characters
for (int i = 0; i < minLen; i++) {
[Link]([Link](i)); // Character from first string
[Link]([Link](i)); // Character from second string }
// Append remaining characters from the longer string
if (len1 > len2) {
[Link]([Link](minLen));
} else if (len2 > len1) {
[Link]([Link](minLen));
}
return [Link]();
}
}
ACC, MIBM & DICA, Sabargam 32
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a java code which accept two strings. Merge both the string in upper
case and display the string in reverse order. Code:- import [Link];
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Accept two strings from the user
[Link]("Enter first string: ");
String str1 = [Link]();
[Link]("Enter second string: ");
String str2 = [Link]();
// Merge and convert to uppercase
String mergedString = (str1 + str2).toUpperCase();
// Reverse the merged string
String reversedString = new StringBuilder(mergedString).reverse().toString();
// Display the reversed string
[Link]("Reversed Merged String: " + reversedString);
[Link]();
}
}
ACC, MIBM & DICA, Sabargam 33
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a program for searching a sub-string from the given sentence entered
by user. If found then also calculate number of times given sub string occur in
given sentence . Also replace it with some other sub-string entered by user.
Code:- import [Link];
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input sentence
[Link]("Enter a sentence: ");
String sentence = [Link]();
// Input substring to search
[Link]("Enter the substring to search: ");
String searchStr = [Link]();
// Input replacement substring
[Link]("Enter the replacement substring: ");
String replaceStr = [Link]();
// Count occurrences of searchStr int count =
countOccurrences(sentence, searchStr);
if (count > 0) {
[Link]("Substring found " + count + " times.");
ACC, MIBM & DICA, Sabargam 34
Roll No:- 320 Name: Singh Roshan
// Replace occurrences
String modifiedSentence = [Link](searchStr, replaceStr);
[Link]("Modified Sentence: " + modifiedSentence);
} else {
[Link]("Substring not found.");
}
[Link]();
}
// Method to count occurrences of a substring public
static int countOccurrences(String str, String sub) { if
([Link]()) return 0;
int count = 0; int index
= [Link](sub);
while (index != -1) {
count++;
index = [Link](sub, index + [Link]());
}
return count;
}
}
Output:-
[Link] your own MyString class in which you have to create method
insertAt(int index, substring s) which will insert substring at given
ACC, MIBM & DICA, Sabargam 35
Roll No:- 320 Name: Singh Roshan
index.(*note: Do not use inbuild insert() function. Use your own logic to
insert substring in given string.) For example. Enter String: He is Raj. Code:-
import [Link];
class MyString {
private String str;
// Constructor public MyString(String
str) {
[Link] = str;
}
// Method to insert substring at given index public
void insertAt(int index, String s) { if
(index < 0 || index > [Link]()) {
[Link]("Invalid index!");
return;
}
// Splitting the original string and inserting the substring
String firstPart = [Link](0, index);
String secondPart = [Link](index);
// Concatenating the parts with the new substring
str = firstPart + s + secondPart;
}
// Method to get the modified string public
String getString() {
return str;
ACC, MIBM & DICA, Sabargam 36
Roll No:- 320 Name: Singh Roshan
}
}
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get input string
[Link]("Enter String: ");
String inputString = [Link]();
// Create MyString object
MyString myString = new MyString(inputString);
// Get index and substring
[Link]("Enter index to insert at: "); int
index = [Link](); [Link]();
// Consume newline
[Link]("Enter substring to insert: ");
String subString = [Link]();
// Perform insertion
[Link](index, subString);
// Display modified string
[Link]("Modified String: " + [Link]());
[Link]();
}
}
ACC, MIBM & DICA, Sabargam 37
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] your own MyString class in which you have to create method
replaceOf(String s1,String s2) which will replace substring s1 with new
substring s2 in given string. (*note: Do not use inbuild replace() function. Use
your own logic to replace substring in given String.) For example. Enter String
: He is Mr. [Link] is my brother. Code:- import [Link];
class MyString {
private String str;
// Constructor public
MyString(String str) {
[Link] = str;
}
// Method to replace all occurrences of s1 with s2 public
void replaceOf(String s1, String s2) {
if ([Link]()) {
[Link]("Cannot replace an empty substring.");
return;
}
StringBuilder result = new StringBuilder();
int i = 0;
int len = [Link]();
ACC, MIBM & DICA, Sabargam 38
Roll No:- 320 Name: Singh Roshan
while (i < [Link]()) {
// Check if the substring s1 is found at the current index
if (i <= [Link]() - len && [Link](i, i + len).equals(s1)) { [Link](s2);
// Append the replacement substring i
+= len; // Move index forward by length of s1
} else {
[Link]([Link](i)); // Append the current character
i++;
}
}
str = [Link]();
}
// Method to get the modified string public
String getString() {
return str;
}
}
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get input string
[Link]("Enter String: ");
String inputString = [Link]();
ACC, MIBM & DICA, Sabargam 39
Roll No:- 320 Name: Singh Roshan
// Create MyString object
MyString myString = new MyString(inputString);
// Get old substring and new substring
[Link]("Enter substring to replace: ");
String oldSubstring = [Link]();
[Link]("Enter new substring: ");
String newSubstring = [Link]();
// Perform replacement
[Link](oldSubstring, newSubstring);
// Display modified string
[Link]("Modified String: " + [Link]());
[Link]();
}
}
Output:-
[Link] your own User defined checked exception MobileNumberException
if user entered mobile number is not valid.(*note: mobile number length
must be 10 digits and only 0 to 9 digits are allowed. Other characters or
symbols are not allowed.) Code:-
import [Link];
ACC, MIBM & DICA, Sabargam 40
Roll No:- 320 Name: Singh Roshan
class MobileNumberException extends Exception { public
MobileNumberException(String message) { super(message);
}
}
public class Purchase {
public static void validateMobileNumber(String mobileNumber) throws
MobileNumberException {
if ([Link]() != 10 || ) {
throw new MobileNumberException(
"Invalid Mobile Number! It must be exactly 10 digits and contain only numbers.");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get user input
[Link]("Enter your mobile number: ");
String mobileNumber = [Link]();
try {
// Validate the mobile number
validateMobileNumber(mobileNumber);
[Link]("Valid Mobile Number: " + mobileNumber);
} catch (MobileNumberException e) {
[Link]("Error: " + [Link]());
}
ACC, MIBM & DICA, Sabargam 41
Roll No:- 320 Name: Singh Roshan
[Link]();
}
}
Output:-
[Link] a program to accept 10 names from the user. Find all the names
which start from ‘j’ and display them at interval of 2 sec. (*note : take the
least 4 to 5 names which start from ‘j’). Code:-
import [Link].*;
public class Purchase { public static void
main(String[] args) {
Scanner scanner = new Scanner([Link]);
ArrayList<String> names = new ArrayList<>();
ArrayList<String> jNames = new ArrayList<>();
// Accept 10 names from the user [Link]("Enter
10 names:");
for (int i = 0; i < 10; i++) {
[Link]("Enter name " + (i + 1) + ": "); String
name = [Link]().trim();
[Link](name);
// Check if name starts with 'J' or 'j' if (![Link]() &&
[Link]([Link](0)) == 'j') {
[Link](name);
}
}
ACC, MIBM & DICA, Sabargam 42
Roll No:- 320 Name: Singh Roshan
[Link]();
// Ensure at least 4-5 names start with 'J'
if ([Link]() < 4) {
[Link]("Please enter at least 4-5 names starting with 'J'. Restart the
program.");
return;
}
// Display names with 2 seconds delay
[Link]("\nNames starting with 'J':"); for
(String name : jNames) {
[Link](name);
try {
[Link](2000); // Pause for 2 seconds
} catch (InterruptedException e) {
[Link]("Error: Thread was interrupted.");
}
}
}
}
Output:-
ACC, MIBM & DICA, Sabargam 43
Roll No:- 320 Name: Singh Roshan
[Link] a program to make a package Balance in which Account class is with
display_Balance method in it. Import balance package in another program to
access display_Balance method of Account class. Code:-
balance/[Link]
package balance; // Define the package
public class Account { private
double balance; //
Constructor public
Account(double balance) {
[Link] = balance;
// Method to display balance public
void display_Balance() {
[Link]("Account Balance: $" + balance);
}
}
[Link] import [Link]; // Import the Account class from the
balance package
public class TestAccount { public static
void main(String[] args) {
// Creating an Account object with an initial balance
Account myAccount = new Account(5000.00);
// Display balance
myAccount.display_Balance();
}
ACC, MIBM & DICA, Sabargam 44
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a program which show the different package sub class concept.
Check the result of different access specifies-private,public,protected and
default.
Code:-
// File: [Link]
package PackageA;
public class Parent { private int privateVar = 10; // Not accessible outside this
class int defaultVar = 20; // Accessible only within the same package protected
int protectedVar = 30; // Accessible within the package and subclasses public int
publicVar = 40; // Accessible everywhere
public void show() {
[Link]("Parent Class: ");
[Link]("Private Variable: " + privateVar);
[Link]("Default Variable: " + defaultVar);
[Link]("Protected Variable: " + protectedVar);
[Link]("Public Variable: " + publicVar);
}
}
// File: [Link]
package packageB; import
[Link]; public
class Child extends Parent { public
void display() {
// [Link]("Private Variable: " + privateVar); // Not accessible
ACC, MIBM & DICA, Sabargam 45
Roll No:- 320 Name: Singh Roshan
// [Link]("Default Variable: " + defaultVar); // Not accessible
[Link]("Protected Variable: " + protectedVar); // Accessible (through
inheritance)
[Link]("Public Variable: " + publicVar); // Accessible
}
}
// File: [Link]
package packageB; import [Link]; public class
MainTest { public static void main(String[] args) { Child obj
= new Child(); [Link](); // Displays only protected
& public members
Parent parentObj = new Parent();
// [Link]("Private Variable: " + [Link]); // Not
// accessible
// [Link]("Default Variable: " + [Link]); // Not
// accessible
// [Link]("Protected Variable: " + [Link]); // Not
// accessible (only through inheritance)
[Link]("Public Variable: " + [Link]); // Accessible
}
}
Output:-
[Link] an applet program which display rotated text of your name at one
place. Code:- import [Link].*; import [Link].*; import
[Link];
ACC, MIBM & DICA, Sabargam 46
Roll No:- 320 Name: Singh Roshan
public class RotatedTextFrame extends JFrame {
public RotatedTextFrame() { setTitle("Rotated Text
Example"); setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new RotatedTextPanel()); setLocationRelativeTo(null);
// Center the window
}
class RotatedTextPanel extends JPanel {
@Override protected void
paintComponent(Graphics g) {
[Link](g);
Graphics2D g2d = (Graphics2D) g;
String name = "Meet"; // Replace with your name
int x = 100, y = 100; // Position of text
double angle = [Link](45); // Rotate by 45 degrees
// Apply rotation transformation
AffineTransform originalTransform = [Link]();
[Link](angle, x, y); [Link](new
Font("Arial", [Link], 20));
[Link]([Link]); [Link](name,
x, y);
// Restore original transform
[Link](originalTransform);
ACC, MIBM & DICA, Sabargam 47
Roll No:- 320 Name: Singh Roshan
}
}
public static void main(String[] args) {
[Link](() -> { new
RotatedTextFrame().setVisible(true);
});
}
}
Output:-
[Link] an applet program which show Digital Clock.
Code:- import [Link].*;
import [Link].*; import
[Link]; import
[Link];
public class DigitalClock extends JFrame { private
JLabel clockLabel;
public DigitalClock() { setTitle("Digital
Clock");
ACC, MIBM & DICA, Sabargam 48
Roll No:- 320 Name: Singh Roshan
setSize(300, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
clockLabel = new JLabel(); [Link](new Font("Arial",
[Link], 30));
[Link]([Link]);
add(clockLabel, [Link]);
// Timer to update the clock every second Timer
timer = new Timer(1000, e -> updateClock());
[Link]();
updateClock(); // Initial clock update setVisible(true);
setLocationRelativeTo(null);
}
private void updateClock() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentTime = [Link](new Date());
[Link](currentTime);
public static void main(String[] args) {
[Link](DigitalClock::new);
}
}
ACC, MIBM & DICA, Sabargam 49
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] an applet program to draw circle in rectangle or only colour in
rectangle. Code:- import [Link].*; import [Link].*;
public class CircleInRectangle extends JFrame {
private boolean drawCircle = true; // Change to false to only fill rectangle
public CircleInRectangle() { setTitle("Circle in Rectangle");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new
DrawingPanel()); setLocationRelativeTo(null);
// Center the window
}
class DrawingPanel extends JPanel {
@Override protected void
paintComponent(Graphics g) {
[Link](g);
Graphics2D g2d = (Graphics2D) g;
int rectX = 50, rectY = 50, rectWidth = 300, rectHeight = 200;
[Link](Color.LIGHT_GRAY); [Link](rectX, rectY,
rectWidth, rectHeight); // Fill rectangle
ACC, MIBM & DICA, Sabargam 50
Roll No:- 320 Name: Singh Roshan
if (drawCircle) { [Link]([Link]);
int circleDiameter = [Link](rectWidth, rectHeight) - 40; int
circleX = rectX + (rectWidth - circleDiameter) / 2; int circleY =
rectY + (rectHeight - circleDiameter) / 2; [Link](circleX,
circleY, circleDiameter, circleDiameter);
}
}
}
public static void main(String[] args) {
[Link](() -> new CircleInRectangle().setVisible(true));
}
}
Output:-
[Link] an applet program which change background colour by click on
different buttons. Code:- import [Link].*; import [Link].*; import
[Link]; import [Link];
ACC, MIBM & DICA, Sabargam 51
Roll No:- 320 Name: Singh Roshan
public class BackgroundColorChanger extends JFrame implements ActionListener { private
JPanel panel;
public BackgroundColorChanger() { setTitle("Background
Color Changer"); setSize(400,
300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create panel to change background color panel
= new JPanel(); add(panel,
[Link]);
// Create buttons panel
JPanel buttonPanel = new JPanel();
add(buttonPanel, [Link]);
// Create buttons with colors
String[] colors = { "Red", "Green", "Blue", "Yellow" };
Color[] colorValues = { [Link], [Link], [Link], [Link] };
for (int i = 0; i < [Link]; i++) { JButton button = new
JButton(colors[i]); [Link](colorValues[i]);
[Link]([Link]); [Link](this);
[Link](colors[i]); // Set action command for identification
[Link](button);
}
setLocationRelativeTo(null); // Center the window
setVisible(true);
ACC, MIBM & DICA, Sabargam 52
Roll No:- 320 Name: Singh Roshan
@Override public void actionPerformed(ActionEvent
e) { switch
([Link]()) {
case "Red":
[Link]([Link]);
break;
case "Green":
[Link]([Link]);
break;
case "Blue":
[Link]([Link]);
break;
case "Yellow":
[Link]([Link]);
break;
}
}
public static void main(String[] args) {
[Link](BackgroundColorChanger::new);
}
}
ACC, MIBM & DICA, Sabargam 53
Roll No:- 320 Name: Singh Roshan
Output:-
[Link] a java program to create Singly Link List to perform create, insert,
delete and display node using menu driven program. Code:-
import [Link];
class Node {
int data;
Node next;
public Node(int data) { [Link]
= data; [Link]
= null;
}
}
class SinglyLinkedList {
private Node head;
public void create(int data) {
if (head == null) {
head = new Node(data);
ACC, MIBM & DICA, Sabargam 54
Roll No:- 320 Name: Singh Roshan
[Link]("List created with first node: " + data);
} else {
[Link]("List already created. Use insert option.");
}
}
public void insert(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node temp = head; while
([Link] != null) {
temp = [Link];
}
[Link] = newNode;
}
[Link]("Node inserted: " + data);
}
public void delete(int data) {
if (head == null) {
[Link]("List is empty.");
return;
}
if ([Link] == data) {
head = [Link]; [Link]("Node
deleted: " + data);
ACC, MIBM & DICA, Sabargam 55
Roll No:- 320 Name: Singh Roshan
return;
}
Node temp = head; while ([Link] != null && [Link]
!= data) { temp = [Link];
}
if ([Link] == null) {
[Link]("Node not found.");
} else {
[Link] = [Link];
[Link]("Node deleted: " + data);
}
}
public void display() { if
(head == null) {
[Link]("List is empty.");
return;
}
Node temp = head;
[Link]("Linked List: "); while
(temp != null) {
[Link]([Link] + " -> ");
temp = [Link];
}
[Link]("NULL");
}
}
public class LinkedListMenu { public
static void main(String[] args) {
ACC, MIBM & DICA, Sabargam 56
Roll No:- 320 Name: Singh Roshan
Scanner scanner = new Scanner([Link]);
SinglyLinkedList list = new SinglyLinkedList(); while
(true) {
[Link]("\nMenu:");
[Link]("1. Create List");
[Link]("2. Insert Node");
[Link]("3. Delete Node");
[Link]("4. Display List");
[Link]("5. Exit");
[Link]("Enter your choice: "); int
choice = [Link](); switch
(choice) {
case 1:
[Link]("Enter data for first node: ");
int firstData = [Link]();
[Link](firstData); break; case 2:
[Link]("Enter data to insert: "); int
data = [Link](); [Link](data);
break; case 3:
[Link]("Enter data to delete: "); int
deleteData = [Link](); [Link](deleteData);
break; case
4:
[Link](); break;
case 5:
[Link]("Exiting program...");
[Link](); return;
default:
[Link]("Invalid choice. Try again.");
ACC, MIBM & DICA, Sabargam 57
Roll No:- 320 Name: Singh Roshan
}
}
}
}
Output:-
[Link] a java program to create Singly Circular List to perform create, insert,
delete and display node using menu driven program. Code:-
import [Link]; class Node
{
int data;
Node next; public
Node(int data) { [Link]
= data; [Link] = null;
}
ACC, MIBM & DICA, Sabargam 58
Roll No:- 320 Name: Singh Roshan
}
class SinglyCircularList { private
Node last;
public SinglyCircularList() {
[Link] = null;
}
public void create(int data) {
if (last != null) {
[Link]("List already exists.");
return;
}
Node newNode = new Node(data);
last = newNode;
[Link] = last;
}
public void insert(int data) {
Node newNode = new Node(data);
if (last == null) {
last = newNode;
[Link] = last;
} else {
[Link] = [Link]; [Link]
= newNode; last
= newNode;
}
}
public void delete(int key) {
ACC, MIBM & DICA, Sabargam 59
Roll No:- 320 Name: Singh Roshan
if (last == null) {
[Link]("List is empty.");
return;
}
Node temp = [Link], prev = last; if
([Link] == key) { if (temp
== last) { last = null; }
else { [Link] =
[Link];
}
return;
}
do {
prev = temp;
temp = [Link]; if ([Link]
== key) { [Link] =
[Link]; if (temp == last) {
last =
prev;
}
return;
}
} while (temp != [Link]);
[Link]("Key not found.");
}
public void display() {
if (last == null) {
[Link]("List is empty.");
return;
ACC, MIBM & DICA, Sabargam 60
Roll No:- 320 Name: Singh Roshan
}
Node temp = [Link];
do {
[Link]([Link] + " -> ");
temp = [Link];
} while (temp != [Link]);
[Link]("(back to head)");
}
}
public class CircularLinkedListApp { public
static void main(String[] args) {
Scanner sc = new Scanner([Link]);
SinglyCircularList list = new SinglyCircularList(); int
choice, data; while (true) {
[Link]("\n1. Create List\n2. Insert Node\n3. Delete Node\n4. Display
List\n5. Exit");
[Link]("Enter choice: ");
choice = [Link](); switch
(choice) {
case 1:
[Link]("Enter data: ");
data = [Link](); [Link](data);
break;
case 2:
[Link]("Enter data: ");
data = [Link](); [Link](data);
break;
case 3:
ACC, MIBM & DICA, Sabargam 61
Roll No:- 320 Name: Singh Roshan
[Link]("Enter value to delete: ");
data = [Link]();
[Link](data); break;
case 4:
[Link](); break;
case 5:
[Link]("Exiting...");
[Link]();
return; default:
[Link]("Invalid choice! Try again.");
}
}
}
}
ACC, MIBM & DICA, Sabargam 62
Roll No:- 320 Name: Singh Roshan
Output:-
ACC, MIBM & DICA, Sabargam 63