Exercise - 2
a) Write a JAVA program using StringBuffer to delete, remove character.
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer sb = new StringBuffer("Hello, World!");
[Link]("Original String: " + sb);
// Deleting a character at index 5 (removes the comma)
[Link](5);
[Link]("After deleting character at index 5: " + sb);
// Removing a substring (delete characters from index 6 to 11)
[Link](6, 11);
[Link]("After deleting substring (index 6 to 11): " + sb);
}
}
Output:
Original String: Hello, World!
After deleting character at index 5: Hello World!
After deleting substring (index 6 to 11): Hello !
Explanation:
1. deleteCharAt(int index) – Removes a single character at the specified position.
2. delete(int start, int end) – Removes a substring between the given start and end
indices.
b) Write a JAVA program to implement class mechanism. Create a class, methods and
invoke them inside main method.
import [Link].*;
// Define a class
class Student {
// Attributes
String name;
int age;
// Method to display student details
void display() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}
// Main class
public class StudentDemo {
public static void main(String[] args) {
// Create an object of the Student class
Student s1 = new Student();
// Assign values to attributes
[Link] = "John";
[Link] = 20;
// Call the method
[Link]();
}
Output:
Student Name: John
Student Age: 20
Explanation:
1. Class Student:
o Has two attributes: name and age.
o A method display() prints student details.
2. Main Class (StudentDemo):
o Creates an object s1 of Student.
o Assigns values to name and age.
o Calls display() to print details.