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!");
System.out.println("Original String: " + sb);
// Deleting a character at index 5 (removes the comma)
sb.deleteCharAt(5);
System.out.println("After deleting character at index 5: " + sb);
// Removing a substring (delete characters from index 6 to 11)
sb.delete(6, 11);
System.out.println("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 java.util.*;
// Define a class
class Student {
// Attributes
String name;
int age;
// Method to display student details
void display() {
System.out.println("Student Name: " + name);
System.out.println("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
s1.name = "John";
s1.age = 20;
// Call the method
s1.display();
}
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.