0% found this document useful (0 votes)
7 views5 pages

Karthi

The document outlines a Java application that implements an Employee class and its derived classes for different job roles, including Programmer, Assistant Professor, Associate Professor, and Professor. It details the structure for generating pay slips based on various salary components like Basic Pay, DA, HRA, PF, and staff club fund. Additionally, it covers inheritance concepts with a Student class and its derived classes, including UG and PG students, along with examples of abstract classes and exception handling in Java.
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)
7 views5 pages

Karthi

The document outlines a Java application that implements an Employee class and its derived classes for different job roles, including Programmer, Assistant Professor, Associate Professor, and Professor. It details the structure for generating pay slips based on various salary components like Basic Pay, DA, HRA, PF, and staff club fund. Additionally, it covers inheritance concepts with a Student class and its derived classes, including UG and PG students, along with examples of abstract classes and exception handling in Java.
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/ 5

Unit 1 void displayDetails() { System.out.

println("\n--- Programmer Pay Slip ---");

System.out.println("Name: " + empName); displayDetails();


Develop a Java application with Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no
as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor and Professor System.out.println("ID: " + empId); System.out.println("Basic Pay: ₹" + basicPay);
from employee class. Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP as
System.out.println("Address: " + address); System.out.println("Gross Salary: ₹" + grossSalary);
DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate pay slips for the
employees with their gross and net salary. System.out.println("Mail ID: " + mailId); System.out.println("Net Salary: ₹" + netSalary);

import java.util.Scanner; System.out.println("Mobile No: " + mobileNo); }

// Base Class } }

class Employee { }

String empName, empId, address, mailId; class AssistantProfessor extends Employee {

long mobileNo; // Derived Classes double basicPay;

class Programmer extends Employee {

void getDetails(Scanner sc) { double basicPay; AssistantProfessor(Scanner sc) {

System.out.print("Enter Employee Name: "); System.out.println("\nEnter Assistant Professor Details:");

empName = sc.nextLine(); Programmer(Scanner sc) { getDetails(sc);

System.out.println("\nEnter Programmer Details:"); System.out.print("Enter Basic Pay: ");

System.out.print("Enter Employee ID: "); getDetails(sc); basicPay = sc.nextDouble();

empId = sc.nextLine(); System.out.print("Enter Basic Pay: "); sc.nextLine();

basicPay = sc.nextDouble(); }

System.out.print("Enter Address: "); sc.nextLine();

address = sc.nextLine(); } void generatePaySlip() {

double da = 0.97 * basicPay;

System.out.print("Enter Mail ID: "); void generatePaySlip() { double hra = 0.10 * basicPay;

mailId = sc.nextLine(); double da = 0.97 * basicPay; double pf = 0.12 * basicPay;

double hra = 0.10 * basicPay; double staffClub = 0.001 * basicPay;

System.out.print("Enter Mobile Number: "); double pf = 0.12 * basicPay; double grossSalary = basicPay + da + hra;

mobileNo = sc.nextLong(); double staffClub = 0.001 * basicPay; double netSalary = grossSalary - pf - staffClub;

sc.nextLine(); // consume newline double grossSalary = basicPay + da + hra;

} double netSalary = grossSalary - pf - staffClub; System.out.println("\n--- Assistant Professor Pay Slip ---");

displayDetails();

System.out.println("Basic Pay: ₹" + basicPay); System.out.println("Net Salary: ₹" + netSalary); }

System.out.println("Gross Salary: ₹" + grossSalary); }

System.out.println("Net Salary: ₹" + netSalary); } // Main Class

} public class EmployeePayrollApp {

} class Professor extends Employee { public static void main(String[] args) {

double basicPay; Scanner sc = new Scanner(System.in);

class AssociateProfessor extends Employee {

double basicPay; Professor(Scanner sc) { // You can create any one or more employee types

System.out.println("\nEnter Professor Details:"); Programmer prog = new Programmer(sc);

AssociateProfessor(Scanner sc) { getDetails(sc); prog.generatePaySlip();

System.out.println("\nEnter Associate Professor Details:"); System.out.print("Enter Basic Pay: ");

getDetails(sc); basicPay = sc.nextDouble(); AssistantProfessor asstProf = new AssistantProfessor(sc);

System.out.print("Enter Basic Pay: "); sc.nextLine(); asstProf.generatePaySlip();

basicPay = sc.nextDouble(); }

sc.nextLine(); AssociateProfessor assocProf = new AssociateProfessor(sc);

} void generatePaySlip() { assocProf.generatePaySlip();

double da = 0.97 * basicPay;

void generatePaySlip() { double hra = 0.10 * basicPay; Professor prof = new Professor(sc);

double da = 0.97 * basicPay; double pf = 0.12 * basicPay; prof.generatePaySlip();

double hra = 0.10 * basicPay; double staffClub = 0.001 * basicPay;

double pf = 0.12 * basicPay; double grossSalary = basicPay + da + hra; sc.close();

double staffClub = 0.001 * basicPay; double netSalary = grossSalary - pf - staffClub; }

double grossSalary = basicPay + da + hra; }

double netSalary = grossSalary - pf - staffClub; System.out.println("\n--- Professor Pay Slip ---"); Output

displayDetails(); Enter Programmer Details:

System.out.println("\n--- Associate Professor Pay Slip ---"); System.out.println("Basic Pay: ₹" + basicPay); Enter Employee Name: Alice

displayDetails(); System.out.println("Gross Salary: ₹" + grossSalary); Enter Employee ID: P001

System.out.println("Basic Pay: ₹" + basicPay); System.out.println("Net Salary: ₹" + netSalary); Enter Address: Chennai

System.out.println("Gross Salary: ₹" + grossSalary); } Enter Mail ID: [email protected]


Enter Mobile Number: 9876543210 // UG Student inherits Student }

Enter Basic Pay: 50000 class UGStudent extends Student { }

protected String course;

--- Programmer Pay Slip --- // Local UG Student inherits UGStudent

Name: Alice public UGStudent(int rollNo, String name, int age, String course) { class LocalUGStudent extends UGStudent {

ID: P001 super(rollNo, name, age); private String location = "Local";

... this.course = course;

Gross Salary: ₹103500.0 } public LocalUGStudent(int rollNo, String name, int age, String course) {

Net Salary: ₹97299.0 super(rollNo, name, age, course);

Unit 2 @Override }

Consider a class student .Inherit this class in UG Student and Evaluate PG Student. Also inherit students public void displayInfo() {

into local and non-local students. Define five Local UG Students with a constructor assuming all classes super.displayInfo(); @Override
have a constructor
System.out.println("Course: " + course); public void displayInfo() {
// Base class
} System.out.println("\n--- Local UG Student ---");
class Student {
} super.displayInfo();
protected int rollNo;
System.out.println("Location: " + location);
protected String name;
// PG Student inherits Student }
protected int age;
class PGStudent extends Student { }

protected String specialization;


public Student(int rollNo, String name, int age) {
// Non-local UG Student inherits UGStudent
this.rollNo = rollNo;
public PGStudent(int rollNo, String name, int age, String specialization) { class NonLocalUGStudent extends UGStudent {
this.name = name;
super(rollNo, name, age); private String location = "Non-Local";
this.age = age;
this.specialization = specialization;
}
} public NonLocalUGStudent(int rollNo, String name, int age, String course) {

super(rollNo, name, age, course);


public void displayInfo() {
@Override }
System.out.println("Roll No: " + rollNo + ", Name: " + name + ", Age: " + age);
public void displayInfo() {
}
super.displayInfo(); @Override
}
System.out.println("Specialization: " + specialization); public void displayInfo() {

System.out.println("\n--- Non-Local UG Student ---"); abstract void printArea();

super.displayInfo(); --- Local UG Student --- }

System.out.println("Location: " + location); Roll No: 102, Name: Bala, Age: 19

} Course: AI & DS // Rectangle class

} Location: Local class Rectangle extends Shape {

Rectangle(int length, int breadth) {

// Main class --- Local UG Student --- this.a = length;

public class StudentInheritanceTest { Roll No: 103, Name: Charan, Age: 18 this.b = breadth;

public static void main(String[] args) { Course: Electronics }

// Creating 5 Local UG Students Location: Local

LocalUGStudent s1 = new LocalUGStudent(101, "Arun", 18, "Computer Science"); void printArea() {

LocalUGStudent s2 = new LocalUGStudent(102, "Bala", 19, "AI & DS"); --- Local UG Student --- int area = a * b;

LocalUGStudent s3 = new LocalUGStudent(103, "Charan", 18, "Electronics"); Roll No: 104, Name: Deepa, Age: 20 System.out.println("Area of Rectangle = " + area);

LocalUGStudent s4 = new LocalUGStudent(104, "Deepa", 20, "Mechanical"); Course: Mechanical }

LocalUGStudent s5 = new LocalUGStudent(105, "Esha", 21, "Civil"); Location: Local }

// Display their information --- Local UG Student --- // Triangle class

s1.displayInfo(); Roll No: 105, Name: Esha, Age: 21 class Triangle extends Shape {

s2.displayInfo(); Course: Civil Triangle(int base, int height) {

s3.displayInfo(); Location: Local this.a = base;

s4.displayInfo(); Unit 3 this.b = height;

s5.displayInfo(); Write a Java Program to create an abstract class named Shape that contains two integers and an empty }

}
method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each
one of the classes extends the class Shape. Each one of the classes contains only the method print Area
} () that prints the area of the given shape void printArea() {

Output double area = 0.5 * a * b;


// Abstract class

--- Local UG Student --- System.out.println("Area of Triangle = " + area);


abstract class Shape {

Roll No: 101, Name: Arun, Age: 18 }


int a, b;

Course: Computer Science }

Location: Local
// Abstract method
// Circle class 2.a) What do you mean by static class and static method? Can we make an instance of an abstract class? int result = MathUtility.square(5);
System.out.println("Square: " + result); // Output: Square: 25
class Circle extends Shape {
Justify your answer with an example? (8 marks) b) What are the various types of exceptions available in }
Java? Also discuss on how they are handled? }
Circle(int radius) {

this.a = radius; a) Static Class and Static Method + Abstract Class Instantiation (8 Marks)
3. Can we instantiate an abstract class?
} 1. Static Class in Java:
No, we cannot create an object of an abstract class directly.
 Definition: A static class is a nested class that is declared as static.
void printArea() {  It can’t access instance methods and variables of the outer class directly. ✅ Justification:
 It is used when the inner class does not require access to the instance members of the
double area = 3.14159 * a * a;
outer class.  Abstract classes are incomplete and meant to be extended by subclasses.
 You can only instantiate concrete subclasses that implement all the abstract methods.
System.out.println("Area of Circle = " + area);
✅ Example of Static Class:
} ✅ Example:
java
} CopyEdit java
class Outer { CopyEdit
static class StaticNested { abstract class Animal {
void display() { abstract void sound();
// Main class }
System.out.println("Inside static nested class");
}
public class ShapeTest { class Dog extends Animal {
}
} void sound() {
public static void main(String[] args) { System.out.println("Dog barks");
public class Main { }
Rectangle rectangle = new Rectangle(10, 5); }
public static void main(String[] args) {
Outer.StaticNested obj = new Outer.StaticNested();
Triangle triangle = new Triangle(8, 4); public class Main {
obj.display(); // Output: Inside static nested class
} public static void main(String[] args) {
Circle circle = new Circle(7); // Animal a = new Animal(); // ❌ Compile-time Error
}
Animal d = new Dog(); // ❌ Polymorphic behavior
d.sound(); // Output: Dog barks
}
rectangle.printArea(); // Rectangle Area = 10 * 5 = 50 2. Static Method in Java: }
triangle.printArea(); // Triangle Area = 0.5 * 8 * 4 = 16
 A static method belongs to the class, not the instance.
circle.printArea(); // Circle Area = π * 7^2 = approx 153.93791  Can be called without creating an object of the class. ✅ b) Types of Exceptions in Java and How They Are Handled
 Can access only static data (variables and other static methods).
}
Java exceptions are objects representing an error condition during program execution.
} ✅ Example of Static Method:

Output java
CopyEdit
Area of Rectangle = 50 class MathUtility {
1. Types of Exceptions:
static int square(int x) {
Area of Triangle = 16.0 return x * x; ✅ A. Checked Exceptions (Compile-time exceptions):
}
Area of Circle = 153.93791 }  These are exceptions that the compiler checks.
public class Main {  Must be either handled using try-catch or declared with throws.
public static void main(String[] args) {

Examples:  OutOfMemoryError throw new ArithmeticException("Not eligible to vote");


 StackOverflowError }
}
 IOException }
 SQLException
 ClassNotFoundException
✅ 2. Exception Handling in Java: ✅ Summary:
java
CopyEdit
import java.io.*; ✅ Using try-catch block: Feature Checked Exceptions Unchecked Exceptions Errors
Compile-time check Yes No No
public class CheckedExample { java
Can be handled Yes Optional Rarely handled
public static void main(String[] args) throws IOException { CopyEdit
FileReader file = new FileReader("test.txt"); // may throw try { Examples IOException ArithmeticException StackOverflowError
FileNotFoundException int data = 50 / 0;
file.close(); } catch (ArithmeticException e) {
} System.out.println("Exception caught: " + e.getMessage()); 3.a) Differentiate between classes and interfaces in java. Describe the importance of interfaces by using
} } an example. [8 marks) (b) Write a java program using class and object model to compute the bill in hotel
with suitable constructor to read data and menu to choose item and a variable to read number of items
✅ Using try-catch-finally: selected.item cost is to be initialized in the program.
✅ B. Unchecked Exceptions (Runtime exceptions):
java
 Not checked at compile-time. CopyEdit (a) Difference between Classes and Interfaces in Java + Importance with
try { Example
 Occur during program execution. int[] arr = new int[3];
 Can be handled using try-catch, but it's optional. arr[5] = 50;
} catch (ArrayIndexOutOfBoundsException e) { Feature Class Interface
Examples: System.out.println("Array index is invalid"); class interface
} finally {
Keyword used
System.out.println("This block always executes"); Supports single
 ArithmeticException } Inheritance Supports multiple inheritance
inheritance
 NullPointerException
 ArrayIndexOutOfBoundsException Can have private,
✅ Using throws keyword: Access Modifiers
protected, public
All methods are public by default
java java Method Can have fully Only abstract methods (until Java 7), default
CopyEdit CopyEdit Implementation implemented methods and static methods (Java 8+)
public class UncheckedExample { public class ThrowsExample {
public static void main(String[] args) { Constructors Can have constructors Cannot have constructors
static void checkFile() throws IOException {
try { FileReader file = new FileReader("file.txt"); Can have instance
int result = 10 / 0; // throws ArithmeticException Variables Variables are public static final by default
} variables
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!"); public static void main(String[] args) throws IOException {
Object creation Can create objects Cannot create object** of interface
} checkFile();
} }
} } ✅ Importance of Interface:
✅ Using throw keyword:  Interfaces help achieve abstraction and loose coupling.
✅ C. Errors:
 Allow multiple inheritance of type.
java
 Not usually handled in programs.  Common in real-time systems to define contracts (what must be done, not how).
CopyEdit
 Occur due to system-level issues. public class ThrowExample {
public static void main(String[] args) {
int age = 10;
Examples: if (age < 18) {
✅ Example: Interface Usage
java Unit 4
CopyEdit void calculateBill() {
interface Payment { double total = itemCost * quantity; Write a Java program to demonstrate the usage of ArrayList and LinkedList. Perform the following
void makePayment(double amount); System.out.println("\n❌ BILL RECEIPT");
operations: add, remove, and retrieve elements. Handle exceptions that may occur during these
} System.out.println("Customer: " + customerName);
System.out.println("Item Price: ₹" + itemCost); operations
class CreditCard implements Payment { System.out.println("Quantity: " + quantity);
public void makePayment(double amount) { System.out.println("Total Bill: ₹" + total); import java.util.ArrayList;
System.out.println("Paid ₹" + amount + " using Credit Card"); }
} } import java.util.LinkedList;
}
public class HotelBillingSystem { import java.util.List;
class UPI implements Payment { public static void main(String[] args) {
public void makePayment(double amount) { Scanner scanner = new Scanner(System.in);
System.out.println("Paid ₹" + amount + " using UPI");
} System.out.println("❌ Welcome to Hotel Menu"); public class ListDemo {
} System.out.println("1. Idli - ₹50\n2. Dosa - ₹100\n3. Fried Rice -
₹120\n4. Chicken Curry - ₹150");
public class InterfaceExample {
public static void main(String[] args) { public static void main(String[] args) {
System.out.print("Enter your name: ");
Payment p1 = new CreditCard(); String name = scanner.nextLine();
Payment p2 = new UPI(); // Create ArrayList and LinkedList
System.out.print("Choose item (1-4): ");
p1.makePayment(500.0); List<String> arrayList = new ArrayList<>();
int choice = scanner.nextInt();
p2.makePayment(250.0);
List<String> linkedList = new LinkedList<>();
} System.out.print("Enter quantity: ");
} int qty = scanner.nextInt();

HotelBill bill = new HotelBill(name, choice, qty);


try {
bill.calculateBill();
✅ (b) Java Program to Compute Hotel Bill using Class & Object
// ---- ArrayList Operations ----
scanner.close();
java } System.out.println(" ArrayList Operations:");
CopyEdit }
import java.util.Scanner; arrayList.add("Apple");

class HotelBill { arrayList.add("Banana");


String customerName; ✅ Sample Output:
int itemChoice; arrayList.add("Mango");
int quantity; mathematica
double itemCost; CopyEdit
❌ Welcome to Hotel Menu
// Constructor to read customer name and item details 1. Idli - ₹50 System.out.println("ArrayList after adding elements: " + arrayList);
HotelBill(String name, int itemChoice, int quantity) { 2. Dosa - ₹100
this.customerName = name; 3. Fried Rice - ₹120
this.itemChoice = itemChoice; 4. Chicken Curry - ₹150
this.quantity = quantity; Enter your name: Ramesh arrayList.remove("Banana");
Choose item (1-4): 2
// Assign item cost based on menu choice Enter quantity: 3 System.out.println("ArrayList after removing 'Banana': " + arrayList);
switch (itemChoice) {
case 1: itemCost = 50; break; // Idli ❌ BILL RECEIPT
case 2: itemCost = 100; break; // Dosa Customer: Ramesh
case 3: itemCost = 120; break; // Fried Rice Item Price: ₹100.0 String element1 = arrayList.get(1);
case 4: itemCost = 150; break; // Chicken Curry Quantity: 3
default: itemCost = 0; break; Total Bill: ₹300.0 System.out.println("Retrieved element at index 1: " + element1);
}
}

// Intentionally causing an exception } import java.util.*;

String errorElement = arrayList.get(5);

System.out.println("This won't print: " + errorElement); System.out.println("\n❌ Program completed successfully."); public class MainProgram {

} public static void main(String[] args) {

} catch (IndexOutOfBoundsException e) { } // Collection to store exception messages

System.out.println("❌ Exception in ArrayList: " + e.getMessage()); Output Collection<String> exceptionLog = new ArrayList<>();

} ArrayList Operations:

ArrayList after adding elements: [Apple, Banana, Mango] try {

try { ArrayList after removing 'Banana': [Apple, Mango] String input = "hello world";

// ---- LinkedList Operations ---- Retrieved element at index 1: Mango System.out.println("Original String: " + input);

System.out.println("\n LinkedList Operations:"); ❌ Exception in ArrayList: Index 5 out of bounds for length 2 System.out.println("Reversed: " + StringUtils.reverse(input));

linkedList.add("Car"); System.out.println("Uppercase: " + StringUtils.toUpperCase(input));

linkedList.add("Bike"); LinkedList Operations:

linkedList.add("Train"); LinkedList after adding elements: [Car, Bike, Train] // Intentionally causing an exception

LinkedList after removing index 1: [Car, Train] String nullInput = null;

System.out.println("LinkedList after adding elements: " + linkedList); Retrieved element at index 1: Train System.out.println("Reversed Null: " + StringUtils.reverse(nullInput));

❌ Exception in LinkedList: Index 5 out of bounds for length 2

linkedList.remove(1); } catch (IllegalArgumentException e) {

System.out.println("LinkedList after removing index 1: " + linkedList); ❌ Program completed successfully. System.out.println("❌ Exception: " + e.getMessage());

Write a Java program to import a custom package and use its classes to perform a specific task. Handle exceptionLog.add(e.getMessage());

String element2 = linkedList.get(1);


any exceptions that may occur during the execution of the program and use the Collection interface to }
store information about the exceptions.
System.out.println("Retrieved element at index 1: " + element2);

What it includes: // Displaying exception logs

// Intentionally causing an exception 1. Creating a custom package with a utility class. System.out.println("\n Exception Log:");

String errorElement = linkedList.get(5);


2. Importing the custom package into the main program. for (String error : exceptionLog) {
3. Using the utility class to perform a task (e.g., string manipulation).
System.out.println("This won't print: " + errorElement); 4. Handling exceptions and storing their messages using the Collection interface System.out.println("• " + error);
(List<String>).
}

} catch (IndexOutOfBoundsException e) { }
package myutils;
System.out.println("❌ Exception in LinkedList: " + e.getMessage()); }
import myutils.StringUtils;
public class StringUtils { // 1. String from character array char[] charArray = { 'H', 'e', 'l', 'l', 'o' };

public static String reverse(String input) { char[] charArray = { 'H', 'e', 'l', 'l', 'o' }; String strFromCharArray = new String(charArray);

if (input == null) { String strFromCharArray = new String(charArray); System.out.println("String from char array: " + strFromCharArray);

throw new IllegalArgumentException("Input cannot be null."); System.out.println("String from char array: " + strFromCharArray);

} // 2. String from byte array

return new StringBuilder(input).reverse().toString(); // 2. String from byte array byte[] byteArray = { 65, 66, 67, 68 }; // ASCII values for A, B, C, D

} byte[] byteArray = { 65, 66, 67, 68 }; // ASCII values for A, B, C, D String strFromByteArray = new String(byteArray);

String strFromByteArray = new String(byteArray); System.out.println("String from byte array: " + strFromByteArray);

public static String toUpperCase(String input) { System.out.println("String from byte array: " + strFromByteArray);

if (input == null) { // 3. String from another String

throw new IllegalArgumentException("Input cannot be null."); // 3. String from another String String original = "Java";

} String original = "Java"; String strFromString = new String(original);

return input.toUpperCase(); String strFromString = new String(original); System.out.println("String from another String: " + strFromString);

} System.out.println("String from another String: " + strFromString);

} // 4. String from a portion of character array

Output // 4. String from a portion of character array String strPartialChar = new String(charArray, 1, 3); // 'e', 'l', 'l'

Original String: hello world String strPartialChar = new String(charArray, 1, 3); // 'e', 'l', 'l' System.out.println("String from partial char array: " + strPartialChar);

Reversed: dlrow olleh System.out.println("String from partial char array: " + strPartialChar);

Uppercase: HELLO WORLD // 5. String from a portion of byte array

❌ Exception: Input cannot be null. // 5. String from a portion of byte array String strPartialByte = new String(byteArray, 1, 2); // ASCII: B, C

String strPartialByte = new String(byteArray, 1, 2); // ASCII: B, C System.out.println("String from partial byte array: " + strPartialByte);

Exception Log: System.out.println("String from partial byte array: " + strPartialByte); }

• Input cannot be null. } }

Unit 5 } Develop a Java program that searches for a given substring within a larger string using the indexOf()
Output
method and displays the index of the first occurrence
Write a Java program that demonstrates the usage of different String constructors by creating strings
from character arrays, byte arrays, and other String objects public class StringConstructorsDemo { import java.util.Scanner;

public class StringConstructorsDemo { public static void main(String[] args) {

public static void main(String[] args) { public class SubstringSearch {

// 1. String from character array public static void main(String[] args) {

Scanner scanner = new Scanner(System.in); import java.util.Scanner; System.out.println(" Lower Case: " + concatenated.toLowerCase());

// Input the main string public class StringManipulation { scanner.close();

System.out.print("Enter the main string: "); public static void main(String[] args) { }

String mainString = scanner.nextLine(); Scanner scanner = new Scanner(System.in); }

Output

// Input the substring to search // Get user input strings Enter the first string: Hello

System.out.print("Enter the substring to search: "); System.out.print("Enter the first string: "); Enter the second string: World

String subString = scanner.nextLine(); String str1 = scanner.nextLine();

❌ Concatenated String: HelloWorld

// Find the index of the first occurrence System.out.print("Enter the second string: ");

int index = mainString.indexOf(subString); String str2 = scanner.nextLine(); Enter the character or word to be replaced: World

Enter the new character or word: Java

// Display the result // Concatenation String after Replacement: HelloJava

if (index != -1) { String concatenated = str1 + str2;

System.out.println("❌ Substring found at index: " + index); System.out.println("\n❌ Concatenated String: " + concatenated); Upper Case: HELLOWORLD

} else { Lower Case: helloworld

System.out.println("❌ Substring not found."); // Replacement

} System.out.print("\nEnter the character or word to be replaced: ");

String target = scanner.nextLine();

scanner.close();

} System.out.print("Enter the new character or word: ");

} String replacement = scanner.nextLine();

Output

Enter the main string: Hello, welcome to Java programming! String replacedString = concatenated.replace(target, replacement);

Enter the substring to search: Java System.out.println(" String after Replacement: " + replacedString);

❌ Substring found at index: 21

Write a Java program that demonstrates various string manipulation operations such as concatenation, // Case Conversion

replacement, and case conversion based on user input. System.out.println("\n Upper Case: " + concatenated.toUpperCase());

You might also like