1.
Assignment Title:
Title: Program on Method and Constructor Overloading
2. Student Information:
Name: Shreya Ranjane
PRN: 124A8092
Course Name/Code: Artificial Intelligence & Data Science
Submission Date: 10-03-25
Task 1: StringBuffer Operations
Write a Java program to demonstrate the use of the StringBuffer
class.
Implement functions to:
o Append a string.
o Insert a substring at a specified position.
o Replace a part of the string.
o Reverse the string.
o Find the length and capacity of the StringBuffer.
Task 2: Vector Operations
Write a Java program to demonstrate the use of Vector in Java.
Implement functions to:
o Add elements to a vector.
o Insert an element at a specific index.
o Remove an element from the vector.
o Search for an element in the vector.
o Display the elements in the vector.
4. Approach / Solution Explanation
Task 1: StringBuffer Operations
Overview: The StringBuffer class is used to create mutable
(modifiable) string objects, making it more efficient than String
when frequent modifications are required.
Methodology: Use built-in StringBuffer methods like append(),
insert(), replace(), reverse(), and capacity().
Task 2: Vector Operations
Overview: The Vector class is a dynamic array that can grow and
shrink in size. It is part of the java.util package.
Methodology: Use methods like add(), insertElementAt(), remove(),
contains(), and elementAt() to manipulate the Vector.
5. Code:
import java.util.Vector;
import java.util.Scanner;
public class StringBufferVectorDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// StringBuffer Operations
System.out.print("Enter a string: ");
StringBuffer sb = new StringBuffer(scanner.nextLine());
sb.append(" World!");
System.out.println("After append: " + sb);
sb.insert(5, " Java");
System.out.println("After insert: " + sb);
sb.replace(6, 10, "Program");
System.out.println("After replace: " + sb);
sb.reverse();
System.out.println("After reverse: " + sb);
sb.reverse(); // Reverting back to original order
System.out.println("StringBuffer Length: " + sb.length());
System.out.println("StringBuffer Capacity: " + sb.capacity());
// Vector Operations
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
System.out.println("\nVector Elements: " + vector);
vector.insertElementAt("Mango", 1);
System.out.println("After inserting Mango at index 1: " + vector);
vector.remove("Banana");
System.out.println("After removing Banana: " + vector);
System.out.print("Enter a fruit to search: ");
String searchItem = scanner.nextLine();
if (vector.contains(searchItem)) {
System.out.println(searchItem + " is present in the vector.");
} else {
System.out.println(searchItem + " is not found in the vector.");
}
System.out.println("Final Vector Elements: " + vector);
scanner.close();
}
}
6. Output / Test Cases: